repo_id
stringclasses
875 values
size
int64
974
38.9k
file_path
stringlengths
10
308
content
stringlengths
974
38.9k
openjdk/jdk8
36,515
jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11NSDocumentScannerImpl.java
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 The Apache Software Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2002, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package com.sun.org.apache.xerces.internal.impl; import java.io.IOException; import com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidatorFilter; import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter; import com.sun.org.apache.xerces.internal.util.XMLAttributesImpl; import com.sun.org.apache.xerces.internal.util.XMLSymbols; import com.sun.org.apache.xerces.internal.xni.NamespaceContext; import com.sun.org.apache.xerces.internal.xni.QName; import com.sun.org.apache.xerces.internal.xni.XMLDocumentHandler; import com.sun.org.apache.xerces.internal.xni.XNIException; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException; import com.sun.org.apache.xerces.internal.xni.parser.XMLDocumentSource; import javax.xml.stream.events.XMLEvent; /** * The scanner acts as the source for the document * information which is communicated to the document handler. * * This class scans an XML document, checks if document has a DTD, and if * DTD is not found the scanner will remove the DTD Validator from the pipeline and perform * namespace binding. * * Note: This scanner should only be used when the namespace processing is on! * * <p> * This component requires the following features and properties from the * component manager that uses it: * <ul> * <li>http://xml.org/sax/features/namespaces {true} -- if the value of this * feature is set to false this scanner must not be used.</li> * <li>http://xml.org/sax/features/validation</li> * <li>http://apache.org/xml/features/nonvalidating/load-external-dtd</li> * <li>http://apache.org/xml/features/scanner/notify-char-refs</li> * <li>http://apache.org/xml/features/scanner/notify-builtin-refs</li> * <li>http://apache.org/xml/properties/internal/symbol-table</li> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * <li>http://apache.org/xml/properties/internal/entity-manager</li> * <li>http://apache.org/xml/properties/internal/dtd-scanner</li> * </ul> * * @xerces.internal * * @author Elena Litani, IBM * @author Michael Glavassevich, IBM * @author Sunitha Reddy, Sun Microsystems * @version $Id: XML11NSDocumentScannerImpl.java,v 1.6 2010-11-01 04:39:40 joehw Exp $ */ public class XML11NSDocumentScannerImpl extends XML11DocumentScannerImpl { /** * If is true, the dtd validator is no longer in the pipeline * and the scanner should bind namespaces */ protected boolean fBindNamespaces; /** * If validating parser, make sure we report an error in the * scanner if DTD grammar is missing. */ protected boolean fPerformValidation; // private data // /** DTD validator */ private XMLDTDValidatorFilter fDTDValidator; /** * Saw spaces after element name or between attributes. * * This is reserved for the case where scanning of a start element spans * several methods, as is the case when scanning the start of a root element * where a DTD external subset may be read after scanning the element name. */ private boolean fSawSpace; /** * The scanner is responsible for removing DTD validator * from the pipeline if it is not needed. * * @param validator the DTD validator from the pipeline */ public void setDTDValidator(XMLDTDValidatorFilter validator) { fDTDValidator = validator; } /** * Scans a start element. This method will handle the binding of * namespace information and notifying the handler of the start * of the element. * <p> * <pre> * [44] EmptyElemTag ::= '&lt;' Name (S Attribute)* S? '/>' * [40] STag ::= '&lt;' Name (S Attribute)* S? '>' * </pre> * <p> * <strong>Note:</strong> This method assumes that the leading * '&lt;' character has been consumed. * <p> * <strong>Note:</strong> This method uses the fElementQName and * fAttributes variables. The contents of these variables will be * destroyed. The caller should copy important information out of * these variables before calling this method. * * @return True if element is empty. (i.e. It matches * production [44]. */ protected boolean scanStartElement() throws IOException, XNIException { if (DEBUG_START_END_ELEMENT) System.out.println(">>> scanStartElementNS()"); // Note: namespace processing is on by default fEntityScanner.scanQName(fElementQName); // REVISIT - [Q] Why do we need this local variable? -- mrglavas String rawname = fElementQName.rawname; if (fBindNamespaces) { fNamespaceContext.pushContext(); if (fScannerState == SCANNER_STATE_ROOT_ELEMENT) { if (fPerformValidation) { fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN, "MSG_GRAMMAR_NOT_FOUND", new Object[] { rawname }, XMLErrorReporter.SEVERITY_ERROR); if (fDoctypeName == null || !fDoctypeName.equals(rawname)) { fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN, "RootElementTypeMustMatchDoctypedecl", new Object[] { fDoctypeName, rawname }, XMLErrorReporter.SEVERITY_ERROR); } } } } // push element stack fCurrentElement = fElementStack.pushElement(fElementQName); // attributes boolean empty = false; fAttributes.removeAllAttributes(); do { // spaces boolean sawSpace = fEntityScanner.skipSpaces(); // end tag? int c = fEntityScanner.peekChar(); if (c == '>') { fEntityScanner.scanChar(); break; } else if (c == '/') { fEntityScanner.scanChar(); if (!fEntityScanner.skipChar('>')) { reportFatalError( "ElementUnterminated", new Object[] { rawname }); } empty = true; break; } else if (!isValidNameStartChar(c) || !sawSpace) { // Second chance. Check if this character is a high // surrogate of a valid name start character. if (!isValidNameStartHighSurrogate(c) || !sawSpace) { reportFatalError( "ElementUnterminated", new Object[] { rawname }); } } // attributes scanAttribute(fAttributes); if (fSecurityManager != null && (!fSecurityManager.isNoLimit(fElementAttributeLimit)) && fAttributes.getLength() > fElementAttributeLimit){ fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN, "ElementAttributeLimit", new Object[]{rawname, new Integer(fElementAttributeLimit) }, XMLErrorReporter.SEVERITY_FATAL_ERROR ); } } while (true); if (fBindNamespaces) { // REVISIT: is it required? forbit xmlns prefix for element if (fElementQName.prefix == XMLSymbols.PREFIX_XMLNS) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "ElementXMLNSPrefix", new Object[] { fElementQName.rawname }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // bind the element String prefix = fElementQName.prefix != null ? fElementQName.prefix : XMLSymbols.EMPTY_STRING; // assign uri to the element fElementQName.uri = fNamespaceContext.getURI(prefix); // make sure that object in the element stack is updated as well fCurrentElement.uri = fElementQName.uri; if (fElementQName.prefix == null && fElementQName.uri != null) { fElementQName.prefix = XMLSymbols.EMPTY_STRING; // making sure that the object in the element stack is updated too. fCurrentElement.prefix = XMLSymbols.EMPTY_STRING; } if (fElementQName.prefix != null && fElementQName.uri == null) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "ElementPrefixUnbound", new Object[] { fElementQName.prefix, fElementQName.rawname }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // bind attributes (xmlns are already bound bellow) int length = fAttributes.getLength(); for (int i = 0; i < length; i++) { fAttributes.getName(i, fAttributeQName); String aprefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : XMLSymbols.EMPTY_STRING; String uri = fNamespaceContext.getURI(aprefix); // REVISIT: try removing the first "if" and see if it is faster. // if (fAttributeQName.uri != null && fAttributeQName.uri == uri) { continue; } if (aprefix != XMLSymbols.EMPTY_STRING) { fAttributeQName.uri = uri; if (uri == null) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "AttributePrefixUnbound", new Object[] { fElementQName.rawname, fAttributeQName.rawname, aprefix }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } fAttributes.setURI(i, uri); } } if (length > 1) { QName name = fAttributes.checkDuplicatesNS(); if (name != null) { if (name.uri != null) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNSNotUnique", new Object[] { fElementQName.rawname, name.localpart, name.uri }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } else { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNotUnique", new Object[] { fElementQName.rawname, name.rawname }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } } } // call handler if (empty) { //decrease the markup depth.. fMarkupDepth--; // check that this element was opened in the same entity if (fMarkupDepth < fEntityStack[fEntityDepth - 1]) { reportFatalError( "ElementEntityMismatch", new Object[] { fCurrentElement.rawname }); } fDocumentHandler.emptyElement(fElementQName, fAttributes, null); /*if (fBindNamespaces) { fNamespaceContext.popContext(); }*/ fScanEndElement = true; //pop the element off the stack.. fElementStack.popElement(); } else { if(dtdGrammarUtil != null) dtdGrammarUtil.startElement(fElementQName, fAttributes); if (fDocumentHandler != null) fDocumentHandler.startElement(fElementQName, fAttributes, null); } if (DEBUG_START_END_ELEMENT) System.out.println("<<< scanStartElement(): " + empty); return empty; } // scanStartElement():boolean /** * Scans the name of an element in a start or empty tag. * * @see #scanStartElement() */ protected void scanStartElementName () throws IOException, XNIException { // Note: namespace processing is on by default fEntityScanner.scanQName(fElementQName); // Must skip spaces here because the DTD scanner // would consume them at the end of the external subset. fSawSpace = fEntityScanner.skipSpaces(); } // scanStartElementName() /** * Scans the remainder of a start or empty tag after the element name. * * @see #scanStartElement * @return True if element is empty. */ protected boolean scanStartElementAfterName() throws IOException, XNIException { // REVISIT - [Q] Why do we need this local variable? -- mrglavas String rawname = fElementQName.rawname; if (fBindNamespaces) { fNamespaceContext.pushContext(); if (fScannerState == SCANNER_STATE_ROOT_ELEMENT) { if (fPerformValidation) { fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN, "MSG_GRAMMAR_NOT_FOUND", new Object[] { rawname }, XMLErrorReporter.SEVERITY_ERROR); if (fDoctypeName == null || !fDoctypeName.equals(rawname)) { fErrorReporter.reportError( XMLMessageFormatter.XML_DOMAIN, "RootElementTypeMustMatchDoctypedecl", new Object[] { fDoctypeName, rawname }, XMLErrorReporter.SEVERITY_ERROR); } } } } // push element stack fCurrentElement = fElementStack.pushElement(fElementQName); // attributes boolean empty = false; fAttributes.removeAllAttributes(); do { // end tag? int c = fEntityScanner.peekChar(); if (c == '>') { fEntityScanner.scanChar(); break; } else if (c == '/') { fEntityScanner.scanChar(); if (!fEntityScanner.skipChar('>')) { reportFatalError( "ElementUnterminated", new Object[] { rawname }); } empty = true; break; } else if (!isValidNameStartChar(c) || !fSawSpace) { // Second chance. Check if this character is a high // surrogate of a valid name start character. if (!isValidNameStartHighSurrogate(c) || !fSawSpace) { reportFatalError( "ElementUnterminated", new Object[] { rawname }); } } // attributes scanAttribute(fAttributes); // spaces fSawSpace = fEntityScanner.skipSpaces(); } while (true); if (fBindNamespaces) { // REVISIT: is it required? forbit xmlns prefix for element if (fElementQName.prefix == XMLSymbols.PREFIX_XMLNS) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "ElementXMLNSPrefix", new Object[] { fElementQName.rawname }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // bind the element String prefix = fElementQName.prefix != null ? fElementQName.prefix : XMLSymbols.EMPTY_STRING; // assign uri to the element fElementQName.uri = fNamespaceContext.getURI(prefix); // make sure that object in the element stack is updated as well fCurrentElement.uri = fElementQName.uri; if (fElementQName.prefix == null && fElementQName.uri != null) { fElementQName.prefix = XMLSymbols.EMPTY_STRING; // making sure that the object in the element stack is updated too. fCurrentElement.prefix = XMLSymbols.EMPTY_STRING; } if (fElementQName.prefix != null && fElementQName.uri == null) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "ElementPrefixUnbound", new Object[] { fElementQName.prefix, fElementQName.rawname }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // bind attributes (xmlns are already bound bellow) int length = fAttributes.getLength(); for (int i = 0; i < length; i++) { fAttributes.getName(i, fAttributeQName); String aprefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : XMLSymbols.EMPTY_STRING; String uri = fNamespaceContext.getURI(aprefix); // REVISIT: try removing the first "if" and see if it is faster. // if (fAttributeQName.uri != null && fAttributeQName.uri == uri) { continue; } if (aprefix != XMLSymbols.EMPTY_STRING) { fAttributeQName.uri = uri; if (uri == null) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "AttributePrefixUnbound", new Object[] { fElementQName.rawname, fAttributeQName.rawname, aprefix }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } fAttributes.setURI(i, uri); } } if (length > 1) { QName name = fAttributes.checkDuplicatesNS(); if (name != null) { if (name.uri != null) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNSNotUnique", new Object[] { fElementQName.rawname, name.localpart, name.uri }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } else { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNotUnique", new Object[] { fElementQName.rawname, name.rawname }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } } } // call handler if (fDocumentHandler != null) { if (empty) { //decrease the markup depth.. fMarkupDepth--; // check that this element was opened in the same entity if (fMarkupDepth < fEntityStack[fEntityDepth - 1]) { reportFatalError( "ElementEntityMismatch", new Object[] { fCurrentElement.rawname }); } fDocumentHandler.emptyElement(fElementQName, fAttributes, null); if (fBindNamespaces) { fNamespaceContext.popContext(); } //pop the element off the stack.. fElementStack.popElement(); } else { fDocumentHandler.startElement(fElementQName, fAttributes, null); } } if (DEBUG_START_END_ELEMENT) System.out.println("<<< scanStartElementAfterName(): " + empty); return empty; } // scanStartElementAfterName() /** * Scans an attribute. * <p> * <pre> * [41] Attribute ::= Name Eq AttValue * </pre> * <p> * <strong>Note:</strong> This method assumes that the next * character on the stream is the first character of the attribute * name. * <p> * <strong>Note:</strong> This method uses the fAttributeQName and * fQName variables. The contents of these variables will be * destroyed. * * @param attributes The attributes list for the scanned attribute. */ protected void scanAttribute(XMLAttributesImpl attributes) throws IOException, XNIException { if (DEBUG_START_END_ELEMENT) System.out.println(">>> scanAttribute()"); // name fEntityScanner.scanQName(fAttributeQName); // equals fEntityScanner.skipSpaces(); if (!fEntityScanner.skipChar('=')) { reportFatalError( "EqRequiredInAttribute", new Object[] { fCurrentElement.rawname, fAttributeQName.rawname }); } fEntityScanner.skipSpaces(); // content int attrIndex; if (fBindNamespaces) { attrIndex = attributes.getLength(); attributes.addAttributeNS( fAttributeQName, XMLSymbols.fCDATASymbol, null); } else { int oldLen = attributes.getLength(); attrIndex = attributes.addAttribute( fAttributeQName, XMLSymbols.fCDATASymbol, null); // WFC: Unique Att Spec if (oldLen == attributes.getLength()) { reportFatalError( "AttributeNotUnique", new Object[] { fCurrentElement.rawname, fAttributeQName.rawname }); } } //REVISIT: one more case needs to be included: external PE and standalone is no boolean isVC = fHasExternalDTD && !fStandalone; // REVISIT: it seems that this function should not take attributes, and length scanAttributeValue( this.fTempString, fTempString2, fAttributeQName.rawname, isVC, fCurrentElement.rawname); String value = fTempString.toString(); attributes.setValue(attrIndex, value); attributes.setNonNormalizedValue(attrIndex, fTempString2.toString()); attributes.setSpecified(attrIndex, true); // record namespace declarations if any. if (fBindNamespaces) { String localpart = fAttributeQName.localpart; String prefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : XMLSymbols.EMPTY_STRING; // when it's of form xmlns="..." or xmlns:prefix="...", // it's a namespace declaration. but prefix:xmlns="..." isn't. if (prefix == XMLSymbols.PREFIX_XMLNS || prefix == XMLSymbols.EMPTY_STRING && localpart == XMLSymbols.PREFIX_XMLNS) { // get the internalized value of this attribute String uri = fSymbolTable.addSymbol(value); // 1. "xmlns" can't be bound to any namespace if (prefix == XMLSymbols.PREFIX_XMLNS && localpart == XMLSymbols.PREFIX_XMLNS) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "CantBindXMLNS", new Object[] { fAttributeQName }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // 2. the namespace for "xmlns" can't be bound to any prefix if (uri == NamespaceContext.XMLNS_URI) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "CantBindXMLNS", new Object[] { fAttributeQName }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // 3. "xml" can't be bound to any other namespace than it's own if (localpart == XMLSymbols.PREFIX_XML) { if (uri != NamespaceContext.XML_URI) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "CantBindXML", new Object[] { fAttributeQName }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } // 4. the namespace for "xml" can't be bound to any other prefix else { if (uri == NamespaceContext.XML_URI) { fErrorReporter.reportError( XMLMessageFormatter.XMLNS_DOMAIN, "CantBindXML", new Object[] { fAttributeQName }, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } prefix = localpart != XMLSymbols.PREFIX_XMLNS ? localpart : XMLSymbols.EMPTY_STRING; // Declare prefix in context. Removing the association between a prefix and a // namespace name is permitted in XML 1.1, so if the uri value is the empty string, // the prefix is being unbound. -- mrglavas fNamespaceContext.declarePrefix( prefix, uri.length() != 0 ? uri : null); // bind namespace attribute to a namespace attributes.setURI( attrIndex, fNamespaceContext.getURI(XMLSymbols.PREFIX_XMLNS)); } else { // attempt to bind attribute if (fAttributeQName.prefix != null) { attributes.setURI( attrIndex, fNamespaceContext.getURI(fAttributeQName.prefix)); } } } if (DEBUG_START_END_ELEMENT) System.out.println("<<< scanAttribute()"); } // scanAttribute(XMLAttributes) /** * Scans an end element. * <p> * <pre> * [42] ETag ::= '&lt;/' Name S? '>' * </pre> * <p> * <strong>Note:</strong> This method uses the fElementQName variable. * The contents of this variable will be destroyed. The caller should * copy the needed information out of this variable before calling * this method. * * @return The element depth. */ protected int scanEndElement() throws IOException, XNIException { if (DEBUG_START_END_ELEMENT) System.out.println(">>> scanEndElement()"); // pop context QName endElementName = fElementStack.popElement(); // Take advantage of the fact that next string _should_ be "fElementQName.rawName", //In scanners most of the time is consumed on checks done for XML characters, we can // optimize on it and avoid the checks done for endElement, //we will also avoid symbol table lookup - neeraj.bajaj@sun.com // this should work both for namespace processing true or false... //REVISIT: if the string is not the same as expected.. we need to do better error handling.. //We can skip this for now... In any case if the string doesn't match -- document is not well formed. if (!fEntityScanner.skipString(endElementName.rawname)) { reportFatalError( "ETagRequired", new Object[] { endElementName.rawname }); } // end fEntityScanner.skipSpaces(); if (!fEntityScanner.skipChar('>')) { reportFatalError( "ETagUnterminated", new Object[] { endElementName.rawname }); } fMarkupDepth--; //we have increased the depth for two markup "<" characters fMarkupDepth--; // check that this element was opened in the same entity if (fMarkupDepth < fEntityStack[fEntityDepth - 1]) { reportFatalError( "ElementEntityMismatch", new Object[] { endElementName.rawname }); } // call handler if (fDocumentHandler != null) { fDocumentHandler.endElement(endElementName, null); /*if (fBindNamespaces) { fNamespaceContext.popContext(); }*/ } if(dtdGrammarUtil != null) dtdGrammarUtil.endElement(endElementName); return fMarkupDepth; } // scanEndElement():int public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { super.reset(componentManager); fPerformValidation = false; fBindNamespaces = false; } /** Creates a content Driver. */ protected Driver createContentDriver() { return new NS11ContentDriver(); } // createContentDriver():Driver /** return the next state on the input * * @return int */ public int next() throws IOException, XNIException { //since namespace context should still be valid when the parser is at the end element state therefore //we pop the context only when next() has been called after the end element state was encountered. - nb. if((fScannerLastState == XMLEvent.END_ELEMENT) && fBindNamespaces){ fScannerLastState = -1; fNamespaceContext.popContext(); } return fScannerLastState = super.next(); } /** * Driver to handle content scanning. */ protected final class NS11ContentDriver extends ContentDriver { /** * Scan for root element hook. This method is a hook for * subclasses to add code that handles scanning for the root * element. This method will also attempt to remove DTD validator * from the pipeline, if there is no DTD grammar. If DTD validator * is no longer in the pipeline bind namespaces in the scanner. * * * @return True if the caller should stop and return true which * allows the scanner to switch to a new scanning * Driver. A return value of false indicates that * the content Driver should continue as normal. */ protected boolean scanRootElementHook() throws IOException, XNIException { if (fExternalSubsetResolver != null && !fSeenDoctypeDecl && !fDisallowDoctype && (fValidation || fLoadExternalDTD)) { scanStartElementName(); resolveExternalSubsetAndRead(); reconfigurePipeline(); if (scanStartElementAfterName()) { setScannerState(SCANNER_STATE_TRAILING_MISC); setDriver(fTrailingMiscDriver); return true; } } else { reconfigurePipeline(); if (scanStartElement()) { setScannerState(SCANNER_STATE_TRAILING_MISC); setDriver(fTrailingMiscDriver); return true; } } return false; } // scanRootElementHook():boolean /** * Re-configures pipeline by removing the DTD validator * if no DTD grammar exists. If no validator exists in the * pipeline or there is no DTD grammar, namespace binding * is performed by the scanner in the enclosing class. */ private void reconfigurePipeline() { if (fDTDValidator == null) { fBindNamespaces = true; } else if (!fDTDValidator.hasGrammar()) { fBindNamespaces = true; fPerformValidation = fDTDValidator.validate(); // re-configure pipeline XMLDocumentSource source = fDTDValidator.getDocumentSource(); XMLDocumentHandler handler = fDTDValidator.getDocumentHandler(); source.setDocumentHandler(handler); if (handler != null) handler.setDocumentSource(source); fDTDValidator.setDocumentSource(null); fDTDValidator.setDocumentHandler(null); } } // reconfigurePipeline() } }
oracle/fastr
35,831
com.oracle.truffle.r.test/src/com/oracle/truffle/r/test/tck/FastRDebugTest.java
/* * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 3 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 3 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.test.tck; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Source; import org.graalvm.polyglot.Value; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.oracle.truffle.api.debug.Breakpoint; import com.oracle.truffle.api.debug.DebugScope; import com.oracle.truffle.api.debug.DebugStackFrame; import com.oracle.truffle.api.debug.DebugValue; import com.oracle.truffle.api.debug.Debugger; import com.oracle.truffle.api.debug.DebuggerSession; import com.oracle.truffle.api.debug.SuspendAnchor; import com.oracle.truffle.api.debug.SuspendedEvent; import com.oracle.truffle.api.debug.SuspensionFilter; import com.oracle.truffle.api.source.SourceSection; import com.oracle.truffle.r.runtime.data.RPromise.EagerPromise; import com.oracle.truffle.r.runtime.env.REnvironment; import com.oracle.truffle.r.runtime.env.frame.RFrameSlot; import com.oracle.truffle.r.test.generate.FastRSession; import com.oracle.truffle.tck.DebuggerTester; public class FastRDebugTest { static final class TestAction { final Runnable action; final RuntimeException stackTrace; TestAction(Runnable action, RuntimeException stackTrace) { this.action = action; this.stackTrace = stackTrace; } void run() { action.run(); } } static final class TestActionList { final LinkedList<TestAction> actions = new LinkedList<>(); void addLast(Runnable action) { actions.add(new TestAction(action, new RuntimeException())); } void clear() { actions.clear(); } boolean isEmpty() { return actions.isEmpty(); } TestAction removeFirst() { return actions.removeFirst(); } } private Debugger debugger; private DebuggerSession debuggerSession; /** * Actions to perform during the test. */ private final TestActionList run = new TestActionList(); private SuspendedEvent suspendedEvent; /** * Exception thrown during execution of some action from {@link #run}. */ private Throwable ex; /** * trace of the point the created the action that threw ex when executed. */ private Throwable exStackTrace; private Context context; protected final ByteArrayOutputStream out = new ByteArrayOutputStream(); protected final ByteArrayOutputStream err = new ByteArrayOutputStream(); @Before public void before() { suspendedEvent = null; context = FastRSession.getContextBuilder("R", "llvm").in(System.in).out(out).err(err).build(); debugger = context.getEngine().getInstruments().get("debugger").lookup(Debugger.class); debuggerSession = debugger.startSession(event -> { suspendedEvent = event; performWork(); suspendedEvent = null; }); run.clear(); } @After public void dispose() { context.close(); debuggerSession.close(); } private static Source sourceFromText(String code, String name) throws IOException { return Source.newBuilder("R", code, name).interactive(true).build(); } private static Source createFactorial() throws IOException { return sourceFromText("main <- function() {\n" + " res = fac(2)\n" + " res\n" + "}\n" + "fac <- function(n) {\n" + " if (n <= 1) {\n" + " 1\n" + " } else {\n" + " nMinusOne = n - 1\n" + " nMOFact = Recall(n - 1)\n" + " res = n * nMOFact\n" + " res\n" + " }\n" + "}\n", "factorial.r"); } private static Source createRStatements() throws IOException { return sourceFromText("foo <- function(a) {\n" + " x = 2L * a\n" + "}\n" + "foo(1)\n" + "x <- 1:100\n" + "print(foo(x))\n" + "y <- sin(x/10)\n" + "print(foo(y))\n" + "z <- cos(x^1.3/(runif(1)*5+10))\n" + "print(foo(z))\n", "statements.r"); } protected final String getOut() { return new String(out.toByteArray()); } protected final String getErr() { try { err.flush(); } catch (IOException e) { } return new String(err.toByteArray()); } @Test public void testBreakpoint() throws Throwable { final Source factorial = createFactorial(); run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); Breakpoint breakpoint = Breakpoint.newBuilder(DebuggerTester.getSourceImpl(factorial)).lineIs(9).build(); debuggerSession.install(breakpoint); }); // Init before eval: performWork(); context.eval(factorial); assertExecutedOK(); assertLocation(9, "nMinusOne = n - 1", "n", 2); continueExecution(); final Source evalSrc = sourceFromText("main()\n", "test.r"); final Value value = context.eval(evalSrc); assertExecutedOK(); Assert.assertEquals("[1] 2\n", getOut()); final int i = value.asInt(); assertEquals("Factorial computed OK", 2, i); } @Test public void testConditionalBreakpoint() throws Throwable { final Source source = sourceFromText("main <- function() { res <- 0;\n" + " for(i in seq(10)) {\n" + " res <- res + i\n" + " }\n" + " res\n" + "}\n", "test.r"); run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); Breakpoint breakpoint = Breakpoint.newBuilder(DebuggerTester.getSourceImpl(source)).lineIs(3).build(); breakpoint.setCondition("i == 5"); debuggerSession.install(breakpoint); }); // Init before eval: performWork(); context.eval(source); assertExecutedOK(); assertLocation(3, "res <- res + i", "i", 5); continueExecution(); final Source evalSrc = sourceFromText("main()\n", "test2.r"); Value result = context.eval(evalSrc); assertExecutedOK(); assertEquals("result is correct", 55, result.asInt()); } @Test public void stepInStepOver() throws Throwable { final Source factorial = createFactorial(); context.eval(factorial); // @formatter:on run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.suspendNextExecution(); }); stepInto(1); assertLocation(2, "res = fac(2)"); stepInto(2); assertLocation(9, "nMinusOne = n - 1", "n", 2); stepOver(1); assertLocation(10, "nMOFact = Recall(n - 1)", "n", 2, "nMinusOne", 1); stepOver(1); assertLocation(11, "res = n * nMOFact", "n", 2, "nMinusOne", 1, "nMOFact", 1); assertMetaObjectsOrStringValues(factorial, true, "n", "double", "nMOFact", "double", "nMinusOne", "double"); stepOver(1); assertLocation(12, "res", "n", 2, "nMinusOne", 1, "nMOFact", 1, "res", 2); stepOver(1); assertLocation(2, "fac(2)"); stepOver(1); assertLocation(3, "res", "res", 2); stepOut(); // Init before eval: performWork(); final Source evalSource = sourceFromText("main()\n", "evaltest.r"); final Value value = context.eval(evalSource); assertExecutedOK(); Assert.assertEquals("[1] 2\n", getOut()); final int i = value.asInt(); assertEquals("Factorial computed OK", 2, i); } @Test public void testFindMetaObjectAndSourceLocation() throws Throwable { final Source source = sourceFromText("main <- function() {\n" + " i = 3L\n" + " n = 15\n" + " str = 'hello'\n" + " i <- i + 1L\n" + " i\n" + "}\n", "test.r"); context.eval(source); // @formatter:on run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.suspendNextExecution(); }); stepInto(1); stepOver(3); assertLocation(5, "i <- i + 1L", "i", 3, "n", 15, "str", "[1] \"hello\""); assertMetaObjectsOrStringValues(source, true, "i", "integer", "n", "double", "str", "character"); stepOut(); performWork(); final Source evalSource = sourceFromText("main()\n", "evaltest.r"); context.eval(evalSource); assertExecutedOK(); } @Test public void testScopeFunction() throws Throwable { final Source srcFunMain = sourceFromText("function () {\n" + " i = 3L\n" + " n = 15L\n" + " str = \"hello\"\n" + " i <- i + 1L\n" + " ab <<- i\n" + " i\n" + "}", "testFunc.r"); final Source source = sourceFromText("x <- 10L\n" + "makeActiveBinding('ab', function(v) { if(missing(v)) x else x <<- v }, .GlobalEnv)\n" + "main <- " + srcFunMain.getCharacters() + "\n", "test.r"); context.eval(source); // @formatter:on run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.suspendNextExecution(); }); assertLocation(1, "main()", "x", 10, "ab", 10, "main", srcFunMain.getCharacters()); stepInto(1); assertLocation(4, "i = 3L"); stepOver(1); assertLocation(5, "n = 15L", "i", 3); stepOver(1); assertLocation(6, "str = \"hello\"", "i", 3, "n", 15); stepOver(1); assertLocation(7, "i <- i + 1L", "i", 3, "n", 15, "str", "[1] \"hello\""); stepOver(1); assertLocation(8, "ab <<- i", "i", 4, "n", 15, "str", "[1] \"hello\""); stepOver(1); assertScope(9, "i", true, false, "ab", 4, "x", 4); stepOut(); assertLocation(1, "main()", "x", 4, "ab", 4, "main", srcFunMain.getCharacters()); performWork(); final Source evalSource = sourceFromText("main()\n", "evaltest.r"); context.eval(evalSource); assertExecutedOK(); } @Test public void testScopePromise() throws Throwable { final Source source = sourceFromText("main <- function(e) {\n" + " x <- 10L\n" + " e()\n" + " x\n" + "}\n" + "closure <- function() {\n" + " x <<- 123L\n" + " x\n" + "}\n", "test.r"); context.eval(source); // @formatter:on run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.suspendNextExecution(); }); stepOver(1); stepInto(1); stepOver(1); assertScope(3, "e()", false, false, "x", 10); stepInto(1); assertLocation(7, "x <<- 123L"); assertScope(7, "x <<- 123L", true, false, "x", 0); stepOver(1); assertScope(8, "x", true, false, "x", 123); continueExecution(); performWork(); final Source evalSource = sourceFromText("x <- 0L\nmain(closure)\n", "evaltest.r"); context.eval(evalSource); assertExecutedOK(); } @Test public void testScopeArguments() throws Throwable { final Source source = sourceFromText("main <- function(a, b, c, d) {\n" + " x <- 10L\n" + "}\n" + "closure <- function() {\n" + " x <<- 123L\n" + " x\n" + "}\n", "test.r"); context.eval(source); // @formatter:on run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.suspendNextExecution(); }); stepInto(1); assertScope(2, "x <- 10L", false, true, "a", 1, "b", 2, "c", 3, "d", 4); continueExecution(); performWork(); final Source evalSource = sourceFromText("main(1, 2, 3, 4)\n", "evaltest.r"); context.eval(evalSource); assertExecutedOK(); } @Test public void testChangedScopeChain() throws Throwable { final Source source = sourceFromText("main <- function(e) {\n" + " x <- 10L\n" + " environment(e) <- environment()\n" + " e()\n" + " x\n" + "}\n" + "closure <- function() {\n" + " x <<- 123L\n" + " x\n" + "}\n", "test.r"); context.eval(source); // @formatter:on run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.suspendNextExecution(); }); stepOver(1); stepInto(1); stepOver(2); assertScope(4, "e()", false, false, "x", 10); stepInto(1); assertLocation(8, "x <<- 123L"); assertScope(8, "x <<- 123L", true, false, "x", 10); stepOver(1); stepOut(); assertScope(9, "x", false, false, "x", 123); assertIdentifiers(false, "x", "e"); stepOut(); assertScope(9, "x", false, false, "x", 0); continueExecution(); performWork(); final Source evalSource = sourceFromText("x <- 0L\nmain(closure)\n", "evaltest.r"); context.eval(evalSource); assertExecutedOK(); } @Test public void testStepOverStatements() throws Throwable { run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.setSteppingFilter(SuspensionFilter.newBuilder().ignoreLanguageContextInitialization(true).build()); debuggerSession.suspendNextExecution(); }); assertLocation(1, "foo <- function(a) {"); stepOver(1); assertLocation(4, "foo(1)"); stepOver(1); assertLocation(5, "x <- 1:100"); stepOver(1); assertLocation(6, "print(foo(x))"); stepOver(1); assertLocation(7, "y <- sin(x/10)"); stepOver(1); assertLocation(8, "print(foo(y))"); stepOver(1); assertLocation(9, "z <- cos(x^1.3/(runif(1)*5+10))"); stepOver(1); assertLocation(10, "print(foo(z))"); continueExecution(); performWork(); context.eval(createRStatements()); assertExecutedOK(); } @Test public void testValueToString() throws Throwable { Source source = createFactorial(); context.eval(source); run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.suspendNextExecution(); }); stepInto(1); assertLocation(2, "res = fac(2)"); stepInto(1); assertLocation(6, "if (n <= 1) {"); assertMetaObjectsOrStringValues(source, true, "n", "promise"); assertMetaObjectsOrStringValues(source, false, "n", "[1] 2"); continueExecution(); performWork(); final Source evalSource = sourceFromText("main()\n", "evaltest.r"); context.eval(evalSource); assertExecutedOK(); } @Test public void testReenterArgumentsAndValues() throws Throwable { // Test that after a re-enter, arguments are kept and variables are cleared. final Source source = sourceFromText("" + "main <- function () {\n" + " i <- 10\n" + " fnc(i <- i + 1, 20)\n" + "}\n" + "fnc <- function(n, m) {\n" + " x <- n + m\n" + " n <- m - n\n" + " m <- m / 2\n" + " x <- x + n * m\n" + " x\n" + "}\n" + "main()\n", "testReenterArgsAndVals.r"); run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.install(Breakpoint.newBuilder(DebuggerTester.getSourceImpl(source)).lineIs(6).build()); }); assertScope(6, "x <- n + m", false, true, "n", 11, "m", 20); stepOver(4); assertScope(10, "x", false, true, "n", 9, "m", 10, "x", 121); run.addLast(() -> suspendedEvent.prepareUnwindFrame(suspendedEvent.getTopStackFrame())); assertScope(3, "return fnc(i <- i + 1, 20)", false, true, "i", 11); continueExecution(); assertScope(6, "x <- n + m", false, true, "n", 11, "m", 20); continueExecution(); performWork(); Value ret = context.eval(source); assertEquals(121, ret.asInt()); assertExecutedOK(); } @Test public void testActiveBinding() throws Throwable { final Source source = sourceFromText("" + "makeActiveBinding(\"bar\", function(x) { if (missing(x)) { 42; } else { cat(\"setting \", x, \"\\n\"); } }, .GlobalEnv)\n" + "x <- bar\n" + "bar <- 24\n", "activeBindingTest.r"); run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.setSteppingFilter(SuspensionFilter.newBuilder().ignoreLanguageContextInitialization(true).build()); debuggerSession.suspendNextExecution(); }); stepOver(1); assertLocation(2, 1, SuspendAnchor.BEFORE, "x <- bar", false, true); run.addLast(() -> { DebugValue bar = suspendedEvent.getSession().getTopScope("R").getDeclaredValue("bar"); assertTrue(bar.isReadable()); assertTrue(bar.hasReadSideEffects()); assertTrue(bar.hasWriteSideEffects()); if (!run.isEmpty()) { run.removeFirst().run(); } }); stepInto(1); assertLocation(1, 40, SuspendAnchor.BEFORE, "if (missing(x)) { 42; } else { cat(\"setting \", x, \"\\n\"); }", false, true, "x", "missing"); stepOver(1); assertLocation(1, 58, SuspendAnchor.BEFORE, "42", false, true, "x", "missing"); stepOver(1); // Bug: Location is 1, 1, ""; the node is com.oracle.truffle.r.nodes.function.RCallNodeGen // The node has CallTag and SourceSection(source=internal, index=0, length=0, characters=) // Expected: assertLocation(2, 9, SuspendAnchor.AFTER, "x <- bar", false, true); stepOver(1); assertLocation(3, 1, SuspendAnchor.BEFORE, "bar <- 24", false, true); run.addLast(() -> { DebugValue x = suspendedEvent.getSession().getTopScope("R").getDeclaredValue("x"); assertTrue(x.isReadable()); assertFalse(x.hasReadSideEffects()); assertFalse(x.hasWriteSideEffects()); if (!run.isEmpty()) { run.removeFirst().run(); } }); stepInto(1); assertLocation(1, 40, SuspendAnchor.BEFORE, "if (missing(x)) { 42; } else { cat(\"setting \", x, \"\\n\"); }", false, true, "x", 24); stepOver(1); assertLocation(1, 71, SuspendAnchor.BEFORE, "cat(\"setting \", x, \"\\n\")", false, true, "x", 24); stepOver(1); // Expected: assertLocation(3, 10, SuspendAnchor.AFTER, "bar <- 24", false, true, "x", 42); continueExecution(); performWork(); context.eval(source); assertExecutedOK(); } @Test public void testStepOut() throws Throwable { final Source source = sourceFromText("fnc <- function() {\n" + " x <- 10L\n" + " return(x + 10)\n" + "}\n" + "fnc() + fnc()\n", "test.r"); context.eval(source); run.addLast(() -> { assertNull(suspendedEvent); assertNotNull(debuggerSession); debuggerSession.setSteppingFilter(SuspensionFilter.newBuilder().ignoreLanguageContextInitialization(true).build()); debuggerSession.suspendNextExecution(); }); assertLocation(1, "fnc <- function() {"); stepOver(1); assertLocation(5, "fnc() + fnc()"); stepInto(1); assertLocation(2, "x <- 10L"); stepOver(1); assertLocation(3, "return(x + 10)"); stepOut(); assertLocation(5, "fnc()"); stepInto(1); assertLocation(2, "x <- 10L"); continueExecution(); performWork(); context.eval(source); assertExecutedOK(); } private void performWork() { RuntimeException stackTrace = null; try { if (ex == null && !run.isEmpty()) { TestAction action = run.actions.removeFirst(); stackTrace = action.stackTrace; action.run(); } } catch (Throwable e) { ex = e; exStackTrace = stackTrace; } } private void stepOver(final int size) { run.addLast(() -> suspendedEvent.prepareStepOver(size)); } private void stepOut() { run.addLast(() -> suspendedEvent.prepareStepOut(1)); } private void continueExecution() { run.addLast(() -> suspendedEvent.prepareContinue()); } private void stepInto(final int size) { run.addLast(() -> suspendedEvent.prepareStepInto(size)); } private void assertIdentifiers(boolean includeAncestors, String... identifiers) { run.addLast(() -> { final DebugStackFrame frame = suspendedEvent.getTopStackFrame(); DebugScope scope = frame.getScope(); Set<String> actualIdentifiers = new HashSet<>(); do { scope.getDeclaredValues().forEach((x) -> actualIdentifiers.add(x.getName())); } while (includeAncestors && scope != null && !REnvironment.baseEnv().getName().equals(scope.getName())); Set<String> expected = new HashSet<>(); for (String s : identifiers) { expected.add(s); } assertEquals(expected, actualIdentifiers); if (!run.isEmpty()) { run.actions.removeFirst().run(); } }); } private void assertLocation(final int line, final String code, final Object... expectedFrame) { assertLocation(line, -1, null, code, false, false, expectedFrame); } private void assertLocation(final int line, final int column, final SuspendAnchor anchor, final String code, boolean includeAncestors, boolean completeMatch, final Object... expectedFrame) { final RuntimeException trace = new RuntimeException(); run.addLast(() -> { try { assertNotNull(suspendedEvent); if (anchor != null) { assertEquals(anchor, suspendedEvent.getSuspendAnchor()); } SourceSection sourceSection = suspendedEvent.getSourceSection(); final int currentLine; final int currentColumn; if (anchor == null || anchor == SuspendAnchor.BEFORE) { currentLine = sourceSection.getStartLine(); currentColumn = sourceSection.getStartColumn(); } else { currentLine = sourceSection.getEndLine(); currentColumn = sourceSection.getEndColumn(); } assertEquals(line, currentLine); if (column != -1) { assertEquals(column, currentColumn); } String currentCode = sourceSection.getCharacters().toString(); // Trim extra lines in currentCode int nl = currentCode.indexOf('\n'); if (nl >= 0) { currentCode = currentCode.substring(0, nl); } currentCode = currentCode.trim(); assertEquals(code, currentCode); compareScope(line, code, includeAncestors, completeMatch, expectedFrame); } catch (RuntimeException | Error e) { final DebugStackFrame frame = suspendedEvent.getTopStackFrame(); final DebugScope scope = frame.getScope(); if (scope != null) { scope.getDeclaredValues().forEach(var -> { System.out.println(var); }); } trace.printStackTrace(); throw e; } }); } /** * Ensure that the scope at a certain program position contains an expected set of key-value * pairs. * * @param line line number * @param code the code snippet of the program location * @param includeAncestors Include current scope's ancestors for the identifier lookup. * @param completeMatch {@code true} if the defined key-value pairs should be the only pairs in * the scope. * @param expectedFrame the key-value pairs (e.g. {@code "id0", 1, "id1", "strValue"}) */ private void assertScope(final int line, final String code, boolean includeAncestors, boolean completeMatch, final Object... expectedFrame) { final RuntimeException trace = new RuntimeException(); run.addLast(() -> { try { compareScope(line, code, includeAncestors, completeMatch, expectedFrame); } catch (RuntimeException | Error e) { final DebugStackFrame frame = suspendedEvent.getTopStackFrame(); frame.getScope().getDeclaredValues().forEach(var -> { System.out.println(var); }); trace.printStackTrace(); throw e; } }); } private static Object expectedToString(Object val) { if (val instanceof Integer || val instanceof Double) { return "[1] " + val; } return val; } private void compareScope(final int line, final String code, boolean includeAncestors, boolean completeMatch, final Object[] expectedFrame) { final DebugStackFrame frame = suspendedEvent.getTopStackFrame(); final AtomicInteger numFrameVars = new AtomicInteger(0); DebugScope scope = frame.getScope(); if (scope != null) { scope.getDeclaredValues().forEach(var -> { // skip synthetic slots for (RFrameSlot slot : RFrameSlot.values()) { if (slot.toString().equals(var.getName())) { return; } } numFrameVars.incrementAndGet(); }); } if (completeMatch) { assertEquals(line + ": " + code, expectedFrame.length / 2, numFrameVars.get()); } for (int i = 0; i < expectedFrame.length; i = i + 2) { String expectedIdentifier = (String) expectedFrame[i]; Object expectedValue = expectedFrame[i + 1]; expectedValue = expectedToString(expectedValue); String expectedValueStr = (expectedValue != null) ? expectedValue.toString() : null; scope = frame.getScope(); DebugValue value = null; if (scope != null) { do { value = scope.getDeclaredValue(expectedIdentifier); scope = scope.getParent(); } while (includeAncestors && value == null && scope != null && !REnvironment.baseEnv().getName().equals(scope.getName())); } if (value == null) { // Ask the top scope: scope = suspendedEvent.getSession().getTopScope("R"); do { value = scope.getDeclaredValue(expectedIdentifier); scope = scope.getParent(); } while (includeAncestors && value == null && scope != null && !REnvironment.baseEnv().getName().equals(scope.getName())); } assertNotNull("identifier \"" + expectedIdentifier + "\" not found", value); String valueStr = value.toDisplayString(true); assertEquals(line + ": " + code + "; identifier: '" + expectedIdentifier + "'", expectedValueStr, valueStr); } if (!run.isEmpty()) { run.actions.removeFirst().run(); } } Object getRValue(Object value) { // This will only work in simple cases if (value instanceof EagerPromise) { return ((EagerPromise) value).getValue(); } return value; } private void assertExecutedOK() throws Throwable { Assert.assertTrue(getErr(), getErr().isEmpty()); if (ex != null) { if (exStackTrace != null) { System.err.println("Stack trace of the location that created the failed action:"); // Try to print only the interesting frames: StackTraceElement[] items = exStackTrace.getStackTrace(); for (int i = 1; i < Math.min(15, items.length); i++) { String s = items[i].toString(); if (s.startsWith("sun.reflect")) { break; } System.err.println(s); } } if (ex instanceof AssertionError) { throw ex; } else { throw new AssertionError("Error during execution", ex); } } assertTrue("Assuming all requests processed: " + run, run.isEmpty()); } /** * Assert either meta object or string value for a set of variables. * * @param expectedSource expected source in which the values should be examined. * @param metaObjects <code>true</code> for checking metaObject or <code>false</code> for * checking <code>value.toDisplayString(true)</code>. * @param nameAndValuePairs name followed by value (arbitrary number of times). */ private void assertMetaObjectsOrStringValues(final Source expectedSource, boolean metaObjects, final String... nameAndValuePairs) { final RuntimeException trace = new RuntimeException(); run.addLast((Runnable) () -> { try { DebugStackFrame frame = suspendedEvent.getTopStackFrame(); for (int i = 0; i < nameAndValuePairs.length;) { String name = nameAndValuePairs[i++]; String expectedValue = nameAndValuePairs[i++]; boolean found = false; for (DebugValue value : frame.getScope().getDeclaredValues()) { if (name.equals(value.getName())) { if (metaObjects) { DebugValue moDV = value.getMetaObject(); if (moDV != null || expectedValue != null) { String mo = moDV.toDisplayString(true); Assert.assertEquals("MetaObjects of '" + name + "' differ:", expectedValue, mo); } } else { // Check toDisplayString(true) value String valAsString = value.toDisplayString(true); Assert.assertEquals("Unexpected " + name + "toString():", expectedValue, valAsString); } found = true; // Trigger findSourceLocation() call SourceSection sourceLocation = value.getSourceLocation(); if (sourceLocation != null) { Assert.assertEquals("Sources differ", DebuggerTester.getSourceImpl(expectedSource), sourceLocation.getSource()); } } } if (!found) { Assert.fail("DebugValue named '" + name + "' not found."); } } if (!run.isEmpty()) { run.actions.removeFirst().run(); } } catch (RuntimeException | Error e) { final DebugStackFrame frame = suspendedEvent.getTopStackFrame(); frame.getScope().getDeclaredValues().forEach(var -> { System.out.println(var); }); trace.printStackTrace(); throw e; } }); } }
google/bindiff
36,344
java/ui/src/main/java/com/google/security/zynamics/bindiff/gui/tabpanels/projecttabpanel/WorkspaceTabPanelFunctions.java
// Copyright 2011-2024 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.bindiff.gui.tabpanels.projecttabpanel; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.flogger.FluentLogger; import com.google.common.io.ByteStreams; import com.google.security.zynamics.bindiff.config.BinDiffConfig; import com.google.security.zynamics.bindiff.database.MatchesDatabase; import com.google.security.zynamics.bindiff.enums.EFunctionType; import com.google.security.zynamics.bindiff.enums.ESide; import com.google.security.zynamics.bindiff.graph.CombinedGraph; import com.google.security.zynamics.bindiff.graph.nodes.CombinedDiffNode; import com.google.security.zynamics.bindiff.gui.dialogs.AddDiffDialog; import com.google.security.zynamics.bindiff.gui.dialogs.NewDiffDialog; import com.google.security.zynamics.bindiff.gui.dialogs.NewWorkspaceDialog; import com.google.security.zynamics.bindiff.gui.dialogs.ProgressDialog; import com.google.security.zynamics.bindiff.gui.dialogs.directorydiff.DiffPairTableData; import com.google.security.zynamics.bindiff.gui.dialogs.directorydiff.DirectoryDiffDialog; import com.google.security.zynamics.bindiff.gui.dialogs.graphsettings.InitialCallGraphSettingsDialog; import com.google.security.zynamics.bindiff.gui.dialogs.graphsettings.InitialFlowGraphSettingsDialog; import com.google.security.zynamics.bindiff.gui.dialogs.mainsettings.MainSettingsDialog; import com.google.security.zynamics.bindiff.gui.tabpanels.TabPanel; import com.google.security.zynamics.bindiff.gui.tabpanels.TabPanelFunctions; import com.google.security.zynamics.bindiff.gui.tabpanels.TabPanelManager; import com.google.security.zynamics.bindiff.gui.tabpanels.detachedviewstabpanel.FunctionDiffViewTabPanel; import com.google.security.zynamics.bindiff.gui.tabpanels.projecttabpanel.implementations.DirectoryDiffImplementation; import com.google.security.zynamics.bindiff.gui.tabpanels.projecttabpanel.implementations.NewDiffImplementation; import com.google.security.zynamics.bindiff.gui.tabpanels.projecttabpanel.projecttree.WorkspaceTree; import com.google.security.zynamics.bindiff.gui.tabpanels.projecttabpanel.projecttree.treenodes.AbstractTreeNode; import com.google.security.zynamics.bindiff.gui.tabpanels.projecttabpanel.projecttree.treenodes.AllFunctionDiffViewsNode; import com.google.security.zynamics.bindiff.gui.tabpanels.projecttabpanel.projecttree.treenodes.FunctionDiffViewsNode; import com.google.security.zynamics.bindiff.gui.tabpanels.viewtabpanel.ViewTabPanel; import com.google.security.zynamics.bindiff.gui.window.MainWindow; import com.google.security.zynamics.bindiff.io.matches.DiffRequestMessage; import com.google.security.zynamics.bindiff.project.Workspace; import com.google.security.zynamics.bindiff.project.WorkspaceListener; import com.google.security.zynamics.bindiff.project.WorkspaceLoader; import com.google.security.zynamics.bindiff.project.diff.CallGraphViewLoader; import com.google.security.zynamics.bindiff.project.diff.Diff; import com.google.security.zynamics.bindiff.project.diff.DiffListener; import com.google.security.zynamics.bindiff.project.diff.DiffLoader; import com.google.security.zynamics.bindiff.project.diff.FlowGraphViewLoader; import com.google.security.zynamics.bindiff.project.diff.FunctionDiffViewLoader; import com.google.security.zynamics.bindiff.project.matches.DiffMetadata; import com.google.security.zynamics.bindiff.project.rawcallgraph.RawCombinedFunction; import com.google.security.zynamics.bindiff.project.rawcallgraph.RawFunction; import com.google.security.zynamics.bindiff.project.userview.CallGraphViewData; import com.google.security.zynamics.bindiff.resources.Constants; import com.google.security.zynamics.bindiff.utils.BinDiffFileUtils; import com.google.security.zynamics.zylib.disassembly.IAddress; import com.google.security.zynamics.zylib.general.Pair; import com.google.security.zynamics.zylib.general.Triple; import com.google.security.zynamics.zylib.gui.CFileChooser; import com.google.security.zynamics.zylib.gui.CMessageBox; import com.google.security.zynamics.zylib.gui.ProgressDialogs.CUnlimitedProgressDialog; import com.google.security.zynamics.zylib.io.FileUtils; import com.google.security.zynamics.zylib.system.SystemHelpers; import java.awt.BorderLayout; import java.awt.Component; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.tree.TreePath; public final class WorkspaceTabPanelFunctions extends TabPanelFunctions { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private MainSettingsDialog mainSettingsDialog = null; private InitialCallGraphSettingsDialog callGraphSettingsDialog = null; private InitialFlowGraphSettingsDialog flowGraphSettingsDialog = null; private WorkspaceTree workspaceTree; public WorkspaceTabPanelFunctions(MainWindow window, Workspace workspace) { super(window, workspace); } private boolean closeViews(List<ViewTabPanel> viewsToSave, List<ViewTabPanel> viewsToClose) { for (ViewTabPanel viewPanel : viewsToSave) { viewPanel .getController() .getTabPanelManager() .getTabbedPane() .setSelectedComponent(viewPanel); Diff diff = viewPanel.getDiff(); int answer = CMessageBox.showYesNoCancelQuestion( getMainWindow(), String.format( "Save %s '%s'?", diff.isFunctionDiff() ? "Function Diff View" : "Diff View", viewPanel.getView().getViewName())); switch (answer) { case JOptionPane.YES_OPTION: if (viewPanel.getController().closeView(true)) { break; } return false; case JOptionPane.NO_OPTION: viewsToClose.add(viewPanel); break; default: return false; } } for (ViewTabPanel view : viewsToClose) { view.getController().closeView(false); } return true; } public void closeViews(Set<ViewTabPanel> views) { List<ViewTabPanel> viewsToSave = new ArrayList<>(); List<ViewTabPanel> viewsToClose = new ArrayList<>(); for (ViewTabPanel viewPanel : views) { if (viewPanel.getController().hasChanged()) { if (viewPanel.getDiff().isFunctionDiff()) { viewsToSave.add(0, viewPanel); } else { viewsToSave.add(viewPanel); } } else { viewsToClose.add(viewPanel); } } closeViews(viewsToSave, viewsToClose); } private File copyFileIntoNewDiffDir(File newDiffDir, File toCopy) throws IOException { var newFilePath = String.format("%s%s%s", newDiffDir, File.separator, toCopy.getName()); var newFile = new File(newFilePath); ByteStreams.copy(new FileInputStream(toCopy), new FileOutputStream(newFile)); return newFile; } private boolean deleteDiff(Diff diff, boolean deleteFromDisk) { // Remove diff from workspace only removeDiffFromWorkspace(diff); if (deleteFromDisk) { try { if (!diff.isFunctionDiff()) { BinDiffFileUtils.deleteDirectory(new File(diff.getDiffFolder())); } else if (!deleteFunctionDiff(diff)) { CMessageBox.showError( getMainWindow(), String.format("Couldn't delete '%s'.", diff.getMatchesDatabase().toString())); } } catch (IOException e) { logger.atSevere().withCause(e).log("Delete diff failed. Couldn't delete diff folder."); CMessageBox.showError(getMainWindow(), "Delete diff failed. Couldn't delete diff folder."); return false; } } return true; } public boolean deleteDiff(Diff diff) { Diff diffRef = diff == null ? getSelectedDiff() : diff; Pair<Integer, Boolean> answer = CMessageBox.showYesNoQuestionWithCheckbox( getParentWindow(), String.format("Are you sure you want to remove '%s'?\n\n", diffRef.getDiffName()), "Also delete diff contents on disk?"); if (answer.first() != JOptionPane.YES_OPTION) { return false; } return deleteDiff(diffRef, answer.second()); } private boolean deleteFunctionDiff(Diff diffToDelete) { if (!diffToDelete.getMatchesDatabase().delete()) { return false; } var parentFolder = diffToDelete.getMatchesDatabase().getParentFile(); var priBinExportFile = diffToDelete.getExportFile(ESide.PRIMARY); var secBinExportFile = diffToDelete.getExportFile(ESide.SECONDARY); var deletePriExport = true; var deleteSecExport = true; for (Diff diff : getWorkspace().getDiffList(true)) { if (parentFolder.equals(diff.getMatchesDatabase().getParentFile())) { if (diff.getExportFile(ESide.PRIMARY).equals(priBinExportFile)) { deletePriExport = false; } if (diff.getExportFile(ESide.SECONDARY).equals(secBinExportFile)) { deleteSecExport = false; } } } if (deletePriExport && !priBinExportFile.delete()) { return false; } if (deleteSecExport && !secBinExportFile.delete()) { return false; } File[] files = parentFolder.listFiles(); if (files != null && files.length == 0) { AllFunctionDiffViewsNode containerNode = (AllFunctionDiffViewsNode) workspaceTree.getModel().getRoot().getChildAt(0); int removeIndex = -1; for (int index = 0; index < containerNode.getChildCount(); ++index) { FunctionDiffViewsNode child = (FunctionDiffViewsNode) containerNode.getChildAt(index); if (child.getViewDirectory().equals(parentFolder)) { removeIndex = index; child.delete(); containerNode.remove(index); workspaceTree.updateTree(); } } if (removeIndex == containerNode.getChildCount()) { --removeIndex; } if (removeIndex > -1) { var toSelect = (FunctionDiffViewsNode) containerNode.getChildAt(removeIndex); var toSelectPath = new TreePath(toSelect.getPath()); workspaceTree.expandPath(toSelectPath); workspaceTree.setSelectionPath(toSelectPath); } return parentFolder.delete(); } return true; } private MainWindow getParentWindow() { return (MainWindow) SwingUtilities.getWindowAncestor(workspaceTree); } private WorkspaceTabPanel getWorkspaceTabPanel() { return getMainWindow().getController().getTabPanelManager().getWorkspaceTabPanel(); } private boolean isImportThunkView( Diff diff, IAddress primaryFunctionAddr, IAddress secondaryFunctionAddr, boolean infoMsg) { RawFunction priFunction = diff.getCallGraph(ESide.PRIMARY).getFunction(primaryFunctionAddr); RawFunction secFunction = diff.getCallGraph(ESide.SECONDARY).getFunction(secondaryFunctionAddr); if ((priFunction != null && secFunction == null && priFunction.getFunctionType() == EFunctionType.IMPORTED) || (secFunction != null && priFunction == null && secFunction.getFunctionType() == EFunctionType.IMPORTED)) { if (infoMsg) { CMessageBox.showInformation( getMainWindow(), "Cannot open unmatched import thunk view since it doesn't contain any code."); } return true; } if (priFunction != null && priFunction.getFunctionType() == EFunctionType.IMPORTED && secFunction != null && secFunction.getFunctionType() == EFunctionType.IMPORTED) { if (infoMsg) { CMessageBox.showInformation( getMainWindow(), "Cannot open matched import thunk view since it doesn't contain any code."); } return true; } return false; } private void loadWorkspace(File workspaceFile, boolean showProgressDialog) { try { if (getWorkspace().isLoaded()) { getWorkspace().closeWorkspace(); } Workspace workspace = getWorkspace(); var loader = new WorkspaceLoader(workspaceFile, workspace); if (showProgressDialog) { ProgressDialog.show( getMainWindow(), String.format("Loading Workspace '%s'", workspaceFile.getName()), loader); } else { loader.loadMetaData(); } String errorMsg = loader.getErrorMessage(); if (!"".equals(errorMsg)) { logger.atSevere().log("%s", errorMsg); CMessageBox.showError(getMainWindow(), errorMsg); } else { getWorkspace().saveWorkspace(); } } catch (Exception e) { logger.atSevere().withCause(e).log("Load workspace failed. %s", e.getMessage()); CMessageBox.showError( getMainWindow(), String.format("Load workspace failed. %s", e.getMessage())); } } public void loadWorkspace() { String workingDirPath = BinDiffConfig.getInstance().getMainSettings().getWorkspaceDirectory(); if ("".equals(workingDirPath)) { BinDiffConfig.getInstance() .getMainSettings() .setWorkspaceDirectory(SystemHelpers.getUserDirectory()); } var workingDir = new File(BinDiffConfig.getInstance().getMainSettings().getWorkspaceDirectory()); var openFileDlg = new CFileChooser(Constants.BINDIFF_WORKSPACEFILE_EXTENSION, "BinDiff Workspace"); openFileDlg.setDialogTitle("Open Workspace"); openFileDlg.setApproveButtonText("Open"); openFileDlg.setCheckBox("Use as default workspace"); if (workingDir.exists()) { openFileDlg.setCurrentDirectory(workingDir); } if (JFileChooser.APPROVE_OPTION == openFileDlg.showOpenDialog(getMainWindow())) { File workspaceFile = openFileDlg.getSelectedFile(); loadWorkspace(workspaceFile, true); // TODO(cblichmann): Ensure that a new default workspace can only be set after it has been // loaded successfully. // Set default workspace? if (openFileDlg.isSelectedCheckBox()) { BinDiffConfig.getInstance() .getMainSettings() .setDefaultWorkspace(workspaceFile.getAbsolutePath()); } } } public void loadWorkspace(String path) { var workspaceDir = new File(path); if (!workspaceDir.exists()) { String msg = "Load workspace failed. Workspace folder does not exist."; logger.atSevere().log("%s", msg); CMessageBox.showError(getMainWindow(), msg); return; } loadWorkspace(workspaceDir, true); } private void removeDiffFromWorkspace(Diff diff) { assert diff != null; Set<Diff> diffSet = new HashSet<>(); diffSet.add(diff); getWorkspace().getDiffList().remove(diff); closeDiffs(diffSet); diff.removeDiff(); for (WorkspaceListener listener : getWorkspace().getListeners()) { listener.removedDiff(diff); } try { getWorkspace().saveWorkspace(); } catch (SQLException e) { logger.atSevere().withCause(e).log("Couldn't delete temporary files"); CMessageBox.showError(getMainWindow(), "Couldn't delete temporary files: " + e.getMessage()); } } public void addDiff() { try { var addDiffDialog = new AddDiffDialog(getParentWindow(), getWorkspace()); if (!addDiffDialog.getAddButtonPressed()) { return; } File matchesDatabase = addDiffDialog.getMatchesBinary(); File priBinExportFile = addDiffDialog.getBinExportBinary(ESide.PRIMARY); File secBinExportFile = addDiffDialog.getBinExportBinary(ESide.SECONDARY); File diffDir = addDiffDialog.getDestinationDirectory(); File newMatchesDatabase = matchesDatabase; if (!diffDir.equals(matchesDatabase.getParentFile())) { diffDir.mkdir(); newMatchesDatabase = copyFileIntoNewDiffDir(diffDir, matchesDatabase); copyFileIntoNewDiffDir(diffDir, priBinExportFile); copyFileIntoNewDiffDir(diffDir, secBinExportFile); } DiffMetadata matchesMetadata = DiffLoader.preloadDiffMatches(newMatchesDatabase); getWorkspace().addDiff(newMatchesDatabase, matchesMetadata, false); } catch (IOException | SQLException e) { logger.atSevere().withCause(e).log("Add diff failed. Couldn't add diff to workspace"); CMessageBox.showError( getMainWindow(), "Add diff failed. Couldn't add diff to workspace: " + e.getMessage()); } } public void closeDialogs() { if (mainSettingsDialog != null) { mainSettingsDialog.dispose(); } if (flowGraphSettingsDialog != null) { flowGraphSettingsDialog.dispose(); } if (callGraphSettingsDialog != null) { callGraphSettingsDialog.dispose(); } } public boolean closeDiffs(Set<Diff> diffs) { List<ViewTabPanel> viewsToSave = new ArrayList<>(); List<ViewTabPanel> viewsToClose = new ArrayList<>(); for (ViewTabPanel viewPanel : getOpenViews(diffs)) { if (viewPanel.getController().hasChanged()) { if (viewPanel.getDiff().isFunctionDiff()) { viewsToSave.add(0, viewPanel); } else { viewsToSave.add(viewPanel); } } else { viewsToClose.add(viewPanel); } } if (closeViews(viewsToSave, viewsToClose)) { for (Diff diff : diffs) { diff.closeDiff(); } return true; } return false; } public boolean closeWorkspace() { Set<Diff> diffsToClose = new HashSet<>(getWorkspace().getDiffList()); if (!closeDiffs(diffsToClose)) { return false; } getWorkspace().closeWorkspace(); return true; } public boolean deleteFunctionDiffs(List<Diff> diffs) { if (diffs.isEmpty()) { return false; } var msg = new StringBuilder(); msg.append("Are you sure you want to delete this function diff views from disk?\n\n"); int index = 0; for (Diff diff : diffs) { if (index != 0) { msg.append("\n"); } msg.append(String.format("'%s'", diff.getDiffName())); if (index++ == 4 && diffs.size() > 5) { msg.append("\n..."); break; } } int answer = CMessageBox.showYesNoQuestion(getParentWindow(), msg.toString()); if (answer == JOptionPane.YES_OPTION) { boolean success = true; for (Diff diff : diffs) { boolean t = deleteDiff(diff, true); if (success) { success = t; } } return success; } return false; } public void directoryDiff() { // Create a new view MainWindow window = getMainWindow(); Workspace workspace = getWorkspace(); String workspacePath = workspace.getWorkspaceDir().getPath(); var diffDialog = new DirectoryDiffDialog(window, new File(workspacePath)); if (!diffDialog.getDiffButtonPressed()) { return; } String priSourceBasePath = diffDialog.getSourceBasePath(ESide.PRIMARY); String secSourceBasePath = diffDialog.getSourceBasePath(ESide.SECONDARY); List<DiffPairTableData> selectedIdbPairs = diffDialog.getSelectedIdbPairs(); var directoryDiffer = new DirectoryDiffImplementation( window, workspace, priSourceBasePath, secSourceBasePath, selectedIdbPairs); try { ProgressDialog.show(window, "Directory Diffing...", directoryDiffer); } catch (Exception e) { logger.atSevere().withCause(e).log( "Directory diffing aborted because of an unexpected exception"); CMessageBox.showError( window, "Directory diffing aborted because of an unexpected exception."); } if (!directoryDiffer.getDiffingErrorMessages().isEmpty()) { int counter = 0; var errorText = new StringBuilder(); for (String msg : directoryDiffer.getDiffingErrorMessages()) { if (++counter == 10) { errorText.append("..."); break; } errorText.append(msg).append("\n"); } CMessageBox.showError(window, errorText.toString()); } if (!directoryDiffer.getOpeningDiffErrorMessages().isEmpty()) { int counter = 0; var errorText = new StringBuilder(); for (String msg : directoryDiffer.getOpeningDiffErrorMessages()) { if (++counter == 10) { errorText.append("..."); break; } errorText.append(msg).append("\n"); } CMessageBox.showError(window, errorText.toString()); } } public LinkedHashSet<ViewTabPanel> getOpenViews(Set<Diff> diffs) { var openViews = new LinkedHashSet<ViewTabPanel>(); MainWindow window = getMainWindow(); for (ViewTabPanel viewPanel : window.getController().getTabPanelManager().getViewTabPanels()) { // Only close views that belong to current diff Diff diff = viewPanel.getDiff(); if (!diffs.contains(diff)) { continue; } openViews.add(viewPanel); } return openViews; } public Diff getSelectedDiff() { TreePath treePath = getWorkspaceTree().getSelectionModel().getSelectionPath(); AbstractTreeNode node = (AbstractTreeNode) treePath.getLastPathComponent(); return node.getDiff(); } public WorkspaceTree getWorkspaceTree() { return workspaceTree; } public void loadDefaultWorkspace() { String workspacePath = BinDiffConfig.getInstance().getMainSettings().getDefaultWorkspace(); if (workspacePath == null || "".equals(workspacePath)) { return; } var workspaceFile = new File(workspacePath); if (workspaceFile.exists() && workspaceFile.canWrite()) { loadWorkspace(workspaceFile, false); } } public void loadDiff(Diff diff) { if (diff == null) { diff = getSelectedDiff(); } if (diff.isLoaded()) { return; } var diffs = new LinkedHashSet<Diff>(); diffs.add(diff); var diffLoader = new DiffLoader(diffs); var progressDialog = new CUnlimitedProgressDialog( getParentWindow(), Constants.DEFAULT_WINDOW_TITLE, String.format("Loading '%s'", diff.getDiffName()), diffLoader); diffLoader.setProgressDescriptionTarget(progressDialog); progressDialog.setVisible(true); Exception e = progressDialog.getException(); if (e != null) { logger.atSevere().withCause(e).log("%s", e.getMessage()); CMessageBox.showError(getMainWindow(), e.getMessage()); } } public void loadFunctionDiffs() { var diffsToLoad = new LinkedHashSet<Diff>(); for (Diff diff : getWorkspace().getDiffList(true)) { if (!diff.isLoaded()) { diffsToLoad.add(diff); } } loadFunctionDiffs(diffsToLoad); } public void loadFunctionDiffs(LinkedHashSet<Diff> diffsToLoad) { var diffLoader = new DiffLoader(diffsToLoad); var progressDialog = new CUnlimitedProgressDialog( getParentWindow(), Constants.DEFAULT_WINDOW_TITLE, "Loading Function Diffs", diffLoader); diffLoader.setProgressDescriptionTarget(progressDialog); progressDialog.setVisible(true); Exception e = progressDialog.getException(); if (e != null) { logger.atSevere().withCause(e).log("%s", e.getMessage()); CMessageBox.showError(getMainWindow(), e.getMessage()); } } public void newDiff() { MainWindow window = getMainWindow(); Workspace workspace = getWorkspace(); String workspacePath = workspace.getWorkspaceDir().getPath(); var dlg = new NewDiffDialog(window, new File(workspacePath)); if (dlg.getDiffButtonPressed()) { File priIDBFile = dlg.getIdb(ESide.PRIMARY); File secIDBFile = dlg.getIdb(ESide.SECONDARY); File priCallGraphFile = dlg.getBinExportBinary(ESide.PRIMARY); File secCallGraphFile = dlg.getBinExportBinary(ESide.SECONDARY); File destinationFile = dlg.getDestinationDirectory(); var newDiffThread = new NewDiffImplementation( window, workspace, priIDBFile, secIDBFile, priCallGraphFile, secCallGraphFile, destinationFile); try { ProgressDialog.show( getMainWindow(), String.format("New single Diff '%s'", destinationFile.getName()), newDiffThread); } catch (Exception e) { logger.atSevere().withCause(e).log("%s", e.getMessage()); CMessageBox.showError(getMainWindow(), "Unknown error while diffing."); } } } public void newWorkspace() { var workspaceDlg = new NewWorkspaceDialog(getParentWindow(), "New Workspace"); workspaceDlg.setVisible(true); if (!workspaceDlg.isOkPressed()) { return; } if (getWorkspace().isLoaded() && !closeWorkspace()) { return; } String workspacePath = FileUtils.ensureTrailingSlash(workspaceDlg.getWorkspacePath()); var workspaceDir = new File(workspacePath); if (!workspaceDir.exists()) { workspaceDir.mkdir(); } var workspaceFile = new File( String.format( "%s%s.%s", workspacePath, workspaceDlg.getWorkspaceName(), Constants.BINDIFF_WORKSPACEFILE_EXTENSION)); try { getWorkspace().newWorkspace(workspaceFile); if (workspaceDlg.isDefaultWorkspace()) { BinDiffConfig.getInstance() .getMainSettings() .setDefaultWorkspace(workspaceFile.getAbsolutePath()); } } catch (IOException | SQLException e) { logger.atSevere().withCause(e).log(); CMessageBox.showError(getMainWindow(), e.getMessage()); } } public void openCallGraphDiffView(DiffRequestMessage data) { MainWindow window = getMainWindow(); TabPanelManager tabPanelManager = window.getController().getTabPanelManager(); // Create a new view var loader = new CallGraphViewLoader(data, window, tabPanelManager, getWorkspace()); try { ProgressDialog.show(getMainWindow(), "Loading call graph diff", loader); } catch (Exception e) { logger.atSevere().withCause(e).log("Open call graph view failed. Couldn't create graph."); CMessageBox.showError(getMainWindow(), "Open call graph view failed. Couldn't create graph."); } } public void openCallGraphView(MainWindow window, Diff diff) { try { TabPanelManager tabPanelManager = window.getController().getTabPanelManager(); if (diff.getViewManager().containsView(null, null)) { // view is already open tabPanelManager.selectTabPanel(null, null, diff); } else { // Create a new view var loader = new CallGraphViewLoader(diff, getMainWindow(), tabPanelManager, getWorkspace()); ProgressDialog.show( getMainWindow(), String.format("Loading call graph '%s'", diff.getDiffName()), loader); for (DiffListener diffListener : diff.getListener()) { diffListener.loadedView(diff); } } } catch (Exception e) { logger.atSevere().withCause(e).log("Open call graph view failed. Couldn't create graph."); CMessageBox.showError(getMainWindow(), "Open call graph view failed. Couldn't create graph."); } } public void openFlowGraphView( MainWindow window, Diff diff, IAddress primaryFunctionAddr, IAddress secondaryFunctionAddr) { if (isImportThunkView(diff, primaryFunctionAddr, secondaryFunctionAddr, true)) { return; } TabPanelManager tabPanelMgr = window.getController().getTabPanelManager(); if (diff.getViewManager().containsView(primaryFunctionAddr, secondaryFunctionAddr)) { // normal view is already open tabPanelMgr.selectTabPanel(primaryFunctionAddr, secondaryFunctionAddr, diff); return; } try { // create a new view var viewAddrs = new LinkedHashSet<Triple<Diff, IAddress, IAddress>>(); viewAddrs.add(Triple.make(diff, primaryFunctionAddr, secondaryFunctionAddr)); var loader = new FlowGraphViewLoader(getMainWindow(), tabPanelMgr, getWorkspace(), viewAddrs); ProgressDialog.show( getMainWindow(), String.format("Loading flow graph '%s'", diff.getDiffName()), loader); for (DiffListener diffListener : diff.getListener()) { diffListener.loadedView(diff); } } catch (Exception e) { logger.atSevere().withCause(e).log("Open flow graph view failed. Couldn't create graph."); CMessageBox.showError(getMainWindow(), "Open flow graph view failed. Couldn't create graph."); } } public void openFlowGraphViews( MainWindow window, LinkedHashSet<Triple<Diff, IAddress, IAddress>> viewsAddresses) { TabPanelManager tabPanelMgr = window.getController().getTabPanelManager(); var viewsAddrsToOpen = new LinkedHashSet<Triple<Diff, IAddress, IAddress>>(); int importedCounter = 0; for (Triple<Diff, IAddress, IAddress> viewAddrs : viewsAddresses) { Diff diff = viewAddrs.first(); IAddress priAddr = viewAddrs.second(); IAddress secAddr = viewAddrs.third(); if (!diff.getViewManager().containsView(priAddr, secAddr)) { if (isImportThunkView(diff, priAddr, secAddr, false)) { ++importedCounter; } else { viewsAddrsToOpen.add(viewAddrs); } } } if (importedCounter > 0) { CMessageBox.showInformation( getParentWindow(), String.format( "%d import thunk views have not been opened since they do not contain any code.", importedCounter)); if (viewsAddrsToOpen.size() == 0) { return; } } try { // Create a new view var loader = new FlowGraphViewLoader(getMainWindow(), tabPanelMgr, getWorkspace(), viewsAddrsToOpen); ProgressDialog.show(getMainWindow(), "Loading flow graph views", loader); var diffSet = new HashSet<Diff>(); for (Triple<Diff, IAddress, IAddress> entry : viewsAddresses) { Diff diff = entry.first(); if (diffSet.add(diff)) { for (DiffListener diffListener : diff.getListener()) { diffListener.loadedView(diff); } } } } catch (Exception e) { logger.atSevere().withCause(e).log("Open flow graph view failed. Couldn't create graph."); CMessageBox.showError(getMainWindow(), "Open flow graph view failed. Couldn't create graph."); } } public void openFunctionDiffView(DiffRequestMessage data) { try { MainWindow window = getMainWindow(); TabPanelManager tabPanelManager = window.getController().getTabPanelManager(); // create a new view or select the tab which contains the already opened view var loader = new FunctionDiffViewLoader(data, window, tabPanelManager, getWorkspace()); ProgressDialog.show(window, "Loading function diff", loader); if (data.getDiff() != null) { for (DiffListener diffListener : data.getDiff().getListener()) { diffListener.loadedView(data.getDiff()); } } } catch (Exception e) { logger.atSevere().withCause(e).log("Open function diff view failed. Couldn't create graph."); CMessageBox.showError( getMainWindow(), "Open function diff view failed. Couldn't create graph: " + e.getMessage()); } } public void openFunctionDiffView(MainWindow window, Diff diff) { checkArgument(diff.isFunctionDiff()); IAddress priFunctionAddr = diff.getCallGraph(ESide.PRIMARY).getNodes().get(0).getAddress(); IAddress secFunctionAddr = diff.getCallGraph(ESide.SECONDARY).getNodes().get(0).getAddress(); if (isImportThunkView(diff, priFunctionAddr, secFunctionAddr, true)) { return; } // This cannot work because openFunctionDiffView(FunctionDiffSocketXmlData data) // creates currently always a new Diff object. TabPanelManager tabPanelMgr = window.getController().getTabPanelManager(); for (TabPanel tabPanel : tabPanelMgr) { if (tabPanel instanceof FunctionDiffViewTabPanel) { FunctionDiffViewTabPanel functionDiffTabPanel = (FunctionDiffViewTabPanel) tabPanel; Diff curDiff = functionDiffTabPanel.getView().getGraphs().getDiff(); if (curDiff == diff) { tabPanelMgr.getTabbedPane().setSelectedComponent(tabPanel); return; } } } var socketData = new DiffRequestMessage(diff); socketData.setBinExportPath(diff.getExportFile(ESide.PRIMARY).getPath(), ESide.PRIMARY); socketData.setBinExportPath(diff.getExportFile(ESide.SECONDARY).getPath(), ESide.SECONDARY); socketData.setMatchesDBPath(diff.getMatchesDatabase().getPath()); openFunctionDiffView(socketData); } public boolean saveDescription(Diff diff, String description) { try (var matchesDb = new MatchesDatabase(diff.getMatchesDatabase())) { matchesDb.saveDiffDescription(description); return true; } catch (SQLException e) { logger.atSevere().withCause(e).log("Database error. Couldn't save diff description."); CMessageBox.showError( getMainWindow(), "Database error. Couldn't save diff description: " + e.getMessage()); } return false; } public void setTreeNodeContextComponent(Component component) { if (component == null) { return; } JPanel treeNodeCtxContainer = getWorkspaceTabPanel().getTreeNodeContextContainer(); treeNodeCtxContainer.removeAll(); treeNodeCtxContainer.add(component, BorderLayout.CENTER); treeNodeCtxContainer.updateUI(); } public void setWorkspaceTree(WorkspaceTree workspaceTree) { this.workspaceTree = workspaceTree; } public void showInCallGraph(Diff diff, Set<Pair<IAddress, IAddress>> viewAddrPairs) { if (!diff.getViewManager().containsView(null, null)) { openCallGraphView(getMainWindow(), diff); } else { TabPanelManager tabPanelMgr = getMainWindow().getController().getTabPanelManager(); tabPanelMgr.selectTabPanel(null, null, diff); } var nodesToSelect = new ArrayList<CombinedDiffNode>(); var nodesToUnselect = new ArrayList<CombinedDiffNode>(); CallGraphViewData viewData = diff.getViewManager().getCallGraphViewData(diff); if (viewData != null) { CombinedGraph combinedGraph = viewData.getGraphs().getCombinedGraph(); for (CombinedDiffNode node : combinedGraph.getNodes()) { RawCombinedFunction function = (RawCombinedFunction) node.getRawNode(); IAddress priAddr = function.getAddress(ESide.PRIMARY); IAddress secAddr = function.getAddress(ESide.SECONDARY); if (viewAddrPairs.contains(Pair.make(priAddr, secAddr))) { nodesToSelect.add(node); } else { nodesToUnselect.add(node); } } combinedGraph.selectNodes(nodesToSelect, nodesToUnselect); } } public void showInitialCallGraphSettingsDialog() { if (callGraphSettingsDialog == null) { callGraphSettingsDialog = new InitialCallGraphSettingsDialog(getMainWindow()); } callGraphSettingsDialog.setVisible(true); } public void showInitialFlowGraphSettingsDialog() { if (flowGraphSettingsDialog == null) { flowGraphSettingsDialog = new InitialFlowGraphSettingsDialog(getMainWindow()); } flowGraphSettingsDialog.setVisible(true); } public boolean showMainSettingsDialog() { if (mainSettingsDialog == null) { mainSettingsDialog = new MainSettingsDialog(getMainWindow()); } mainSettingsDialog.setVisible(true); return mainSettingsDialog.isCancelled(); } }
oracle/graalpython
36,497
graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/ImpModuleBuiltins.java
/* * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.graal.python.builtins.modules; import static com.oracle.graal.python.builtins.PythonBuiltinClassType.TypeError; import static com.oracle.graal.python.builtins.modules.ImpModuleBuiltins.FrozenStatus.FROZEN_DISABLED; import static com.oracle.graal.python.builtins.modules.ImpModuleBuiltins.FrozenStatus.FROZEN_EXCLUDED; import static com.oracle.graal.python.builtins.modules.ImpModuleBuiltins.FrozenStatus.FROZEN_INVALID; import static com.oracle.graal.python.builtins.modules.ImpModuleBuiltins.FrozenStatus.FROZEN_NOT_FOUND; import static com.oracle.graal.python.builtins.modules.ImpModuleBuiltins.FrozenStatus.FROZEN_OKAY; import static com.oracle.graal.python.nodes.SpecialAttributeNames.T___LOADER__; import static com.oracle.graal.python.nodes.SpecialAttributeNames.T___ORIGNAME__; import static com.oracle.graal.python.nodes.SpecialAttributeNames.T___PATH__; import static com.oracle.graal.python.nodes.StringLiterals.T_EXT_PYD; import static com.oracle.graal.python.nodes.StringLiterals.T_EXT_SO; import static com.oracle.graal.python.nodes.StringLiterals.T_NAME; import static com.oracle.graal.python.runtime.exception.PythonErrorType.NotImplementedError; import static com.oracle.graal.python.util.PythonUtils.TS_ENCODING; import static com.oracle.graal.python.util.PythonUtils.toTruffleStringUncached; import static com.oracle.graal.python.util.PythonUtils.tsLiteral; import java.io.IOException; import java.util.List; import java.util.concurrent.locks.ReentrantLock; import com.oracle.graal.python.PythonLanguage; import com.oracle.graal.python.annotations.ArgumentClinic; import com.oracle.graal.python.annotations.ArgumentClinic.ClinicConversion; import com.oracle.graal.python.annotations.Builtin; import com.oracle.graal.python.builtins.CoreFunctions; import com.oracle.graal.python.builtins.Python3Core; import com.oracle.graal.python.builtins.PythonBuiltinClassType; import com.oracle.graal.python.builtins.PythonBuiltins; import com.oracle.graal.python.builtins.modules.MarshalModuleBuiltins.Marshal.MarshalError; import com.oracle.graal.python.builtins.objects.PNone; import com.oracle.graal.python.builtins.objects.buffer.PythonBufferAccessLibrary; import com.oracle.graal.python.builtins.objects.bytes.BytesNodes; import com.oracle.graal.python.builtins.objects.bytes.PBytes; import com.oracle.graal.python.builtins.objects.cext.capi.CApiContext; import com.oracle.graal.python.builtins.objects.cext.capi.CApiContext.ModuleSpec; import com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes; import com.oracle.graal.python.builtins.objects.cext.common.LoadCExtException.ApiInitException; import com.oracle.graal.python.builtins.objects.cext.common.LoadCExtException.ImportException; import com.oracle.graal.python.builtins.objects.code.PCode; import com.oracle.graal.python.builtins.objects.function.PArguments; import com.oracle.graal.python.builtins.objects.memoryview.PMemoryView; import com.oracle.graal.python.builtins.objects.module.FrozenModules; import com.oracle.graal.python.builtins.objects.module.PythonFrozenModule; import com.oracle.graal.python.builtins.objects.module.PythonModule; import com.oracle.graal.python.builtins.objects.object.PythonObject; import com.oracle.graal.python.builtins.objects.str.PString; import com.oracle.graal.python.builtins.objects.str.StringNodes; import com.oracle.graal.python.compiler.CodeUnit; import com.oracle.graal.python.compiler.Compiler; import com.oracle.graal.python.lib.PyMemoryViewFromObject; import com.oracle.graal.python.lib.PyObjectGetAttr; import com.oracle.graal.python.lib.PyObjectLookupAttr; import com.oracle.graal.python.lib.PyObjectSetAttr; import com.oracle.graal.python.nodes.ErrorMessages; import com.oracle.graal.python.nodes.PConstructAndRaiseNode; import com.oracle.graal.python.nodes.PRaiseNode; import com.oracle.graal.python.nodes.attributes.WriteAttributeToPythonObjectNode; import com.oracle.graal.python.nodes.call.CallDispatchers; import com.oracle.graal.python.nodes.function.PythonBuiltinBaseNode; import com.oracle.graal.python.nodes.function.PythonBuiltinNode; import com.oracle.graal.python.nodes.function.builtins.PythonBinaryBuiltinNode; import com.oracle.graal.python.nodes.function.builtins.PythonBinaryClinicBuiltinNode; import com.oracle.graal.python.nodes.function.builtins.PythonUnaryClinicBuiltinNode; import com.oracle.graal.python.nodes.function.builtins.clinic.ArgumentClinicProvider; import com.oracle.graal.python.nodes.util.CannotCastException; import com.oracle.graal.python.nodes.util.CastToTruffleStringNode; import com.oracle.graal.python.runtime.ExecutionContext.IndirectCallContext; import com.oracle.graal.python.runtime.GilNode; import com.oracle.graal.python.runtime.IndirectCallData; import com.oracle.graal.python.runtime.PythonContext; import com.oracle.graal.python.runtime.PythonOptions; import com.oracle.graal.python.runtime.object.PFactory; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.RootCallTarget; import com.oracle.truffle.api.TruffleSafepoint; import com.oracle.truffle.api.dsl.Bind; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.NodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.memory.ByteArraySupport; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.strings.TruffleString; import com.oracle.truffle.api.utilities.TriState; @CoreFunctions(defineModule = ImpModuleBuiltins.J__IMP, isEager = true) public final class ImpModuleBuiltins extends PythonBuiltins { public static final TruffleString T_ORIGIN = tsLiteral("origin"); static final String J__IMP = "_imp"; public static final TruffleString T__IMP = tsLiteral(J__IMP); private static class FrozenResult { final FrozenStatus status; final FrozenInfo info; FrozenResult(FrozenStatus status) { this(status, null); } FrozenResult(FrozenStatus status, FrozenInfo info) { this.status = status; this.info = info; } } private static class FrozenInfo { @SuppressWarnings("unused") final TruffleString name; final CodeUnit code; final boolean isPackage; final TruffleString origName; @SuppressWarnings("unused") final boolean isAlias; FrozenInfo(TruffleString name, CodeUnit code, boolean isPackage, TruffleString origName, boolean isAlias) { this.name = name; this.code = code; this.isPackage = isPackage; this.origName = origName; this.isAlias = isAlias; } } enum FrozenStatus { FROZEN_OKAY, FROZEN_BAD_NAME, // The given module name wasn't valid. FROZEN_NOT_FOUND, // It wasn't in frozen modules. FROZEN_DISABLED, // -X frozen_modules=off (and not essential) FROZEN_EXCLUDED, // Frozen module has no code. We don't use this in our frozen modules FROZEN_INVALID, // Frozen module has empty code } @Override protected List<? extends NodeFactory<? extends PythonBuiltinBaseNode>> getNodeFactories() { return ImpModuleBuiltinsFactory.getFactories(); } @Override public void postInitialize(Python3Core core) { super.postInitialize(core); PythonContext context = core.getContext(); PythonModule mod = core.lookupBuiltinModule(T__IMP); mod.setAttribute(tsLiteral("check_hash_based_pycs"), context.getOption(PythonOptions.CheckHashPycsMode)); } @Builtin(name = "acquire_lock") @GenerateNodeFactory public abstract static class AcquireLock extends PythonBuiltinNode { @Specialization @TruffleBoundary public Object run(@Cached GilNode gil) { gil.release(true); try { TruffleSafepoint.setBlockedThreadInterruptible(this, ReentrantLock::lockInterruptibly, getContext().getImportLock()); } finally { gil.acquire(); } return PNone.NONE; } } @Builtin(name = "release_lock") @GenerateNodeFactory public abstract static class ReleaseLockNode extends PythonBuiltinNode { @Specialization @TruffleBoundary public Object run() { ReentrantLock importLock = getContext().getImportLock(); if (importLock.isHeldByCurrentThread()) { importLock.unlock(); } return PNone.NONE; } } @Builtin(name = "lock_held") @GenerateNodeFactory public abstract static class LockHeld extends PythonBuiltinNode { @Specialization @TruffleBoundary public boolean run() { ReentrantLock importLock = getContext().getImportLock(); return importLock.isHeldByCurrentThread(); } } @Builtin(name = "get_magic") @GenerateNodeFactory public abstract static class GetMagic extends PythonBuiltinNode { static final int MAGIC_NUMBER = 21000 + Compiler.BYTECODE_VERSION * 10; static final byte[] MAGIC_NUMBER_BYTES = new byte[4]; static { ByteArraySupport.littleEndian().putInt(MAGIC_NUMBER_BYTES, 0, MAGIC_NUMBER); MAGIC_NUMBER_BYTES[2] = '\r'; MAGIC_NUMBER_BYTES[3] = '\n'; } @Specialization(guards = "isSingleContext()") PBytes runCachedSingleContext( @Cached(value = "getMagicNumberPBytes()", weak = true) PBytes magicBytes) { return magicBytes; } @Specialization(replaces = "runCachedSingleContext") PBytes run( @Bind PythonLanguage language) { return PFactory.createBytes(language, MAGIC_NUMBER_BYTES); } protected PBytes getMagicNumberPBytes() { return PFactory.createBytes(PythonLanguage.get(this), MAGIC_NUMBER_BYTES); } } @Builtin(name = "exec_dynamic", minNumOfPositionalArgs = 1, doc = "exec_dynamic($module, mod, /)\n--\n\nInitialize an extension module.") @GenerateNodeFactory public abstract static class ExecDynamicNode extends PythonBuiltinNode { @Specialization static int doPythonModule(VirtualFrame frame, PythonModule extensionModule, @Bind PythonContext context, @Bind Node inliningTarget, @Cached("createFor($node)") IndirectCallData indirectCallData) { Object nativeModuleDef = extensionModule.getNativeModuleDef(); if (nativeModuleDef == null) { return 0; } PythonLanguage language = context.getLanguage(inliningTarget); Object state = IndirectCallContext.enter(frame, language, context, indirectCallData); try { return doExec(inliningTarget, context, extensionModule, nativeModuleDef); } finally { IndirectCallContext.exit(frame, language, context, state); } } @TruffleBoundary private static int doExec(Node node, PythonContext context, PythonModule extensionModule, Object nativeModuleDef) { /* * Check if module is already initialized. CPython does that by testing if 'md_state != * NULL'. So, we do the same. */ Object mdState = extensionModule.getNativeModuleState(); if (mdState != null && !InteropLibrary.getUncached().isNull(mdState)) { return 0; } if (!context.hasCApiContext()) { throw PRaiseNode.raiseStatic(node, PythonBuiltinClassType.SystemError, ErrorMessages.CAPI_NOT_YET_INITIALIZED); } /* * ExecModuleNode will run the module definition's exec function which may run arbitrary * C code. So we need to setup an indirect call. */ return CExtNodes.execModule(node, context.getCApiContext(), extensionModule, nativeModuleDef); } @Fallback static int doOther(@SuppressWarnings("unused") Object extensionModule) { return 0; } } @Builtin(name = "is_builtin", minNumOfPositionalArgs = 1, numOfPositionalOnlyArgs = 1, parameterNames = {"name"}) @ArgumentClinic(name = "name", conversion = ClinicConversion.TString) @GenerateNodeFactory public abstract static class IsBuiltin extends PythonUnaryClinicBuiltinNode { @Specialization @TruffleBoundary public int run(TruffleString name) { if (getContext().lookupBuiltinModule(name) != null) { // TODO: missing "1" case when the builtin module can be re-initialized return -1; } else { return 0; } } @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.IsBuiltinClinicProviderGen.INSTANCE; } } @Builtin(name = "create_builtin", minNumOfPositionalArgs = 1) @GenerateNodeFactory public abstract static class CreateBuiltin extends PythonBuiltinNode { public static final TruffleString T_LOADER = tsLiteral("loader"); @Specialization @TruffleBoundary static Object run(PythonObject moduleSpec, @Bind Node inliningTarget, @Bind PythonContext context) { Object name = PyObjectLookupAttr.executeUncached(moduleSpec, T_NAME); TruffleString nameStr = StringNodes.CastToTruffleStringChecked0Node.getUncached().cast(null, name, ErrorMessages.BAD_ARG_TO_INTERNAL_FUNC); PythonModule builtinModule = context.lookupBuiltinModule(nameStr); if (builtinModule != null) { // TODO: GR-26411 builtin modules cannot be re-initialized (see is_builtin) // We are setting the loader to the spec loader (since this is the loader that is // set during bootstrap); this, however, should be handled be the builtin module // reinitialization (if reinit is possible) Object loader = PyObjectLookupAttr.executeUncached(moduleSpec, T_LOADER); if (loader != PNone.NO_VALUE) { PyObjectSetAttr.executeUncached(builtinModule, T___LOADER__, loader); } return builtinModule; } throw PRaiseNode.raiseStatic(inliningTarget, NotImplementedError, toTruffleStringUncached("_imp.create_builtin")); } } @Builtin(name = "exec_builtin", minNumOfPositionalArgs = 1) @GenerateNodeFactory public abstract static class ExecBuiltin extends PythonBuiltinNode { @Specialization @TruffleBoundary public Object exec(PythonModule pythonModule) { final PythonContext context = getContext(); if (!context.getEnv().isPreInitialization()) { final PythonBuiltins builtins = pythonModule.getBuiltins(); assert builtins != null; // this is a builtin, therefore its builtins must have been // set at this point if (!builtins.isInitialized()) { doPostInit(context, builtins); builtins.setInitialized(true); } } return PNone.NONE; } @TruffleBoundary private static void doPostInit(Python3Core core, PythonBuiltins builtins) { builtins.postInitialize(core); } } @Builtin(name = "is_frozen", parameterNames = {"name"}, minNumOfPositionalArgs = 1, doc = "is_frozen($module, name, /)\\n\"\n" + "--\n" + "\n" + "Returns True if the module name corresponds to a frozen module.") @GenerateNodeFactory @ArgumentClinic(name = "name", conversion = ArgumentClinic.ClinicConversion.TString) abstract static class IsFrozen extends PythonUnaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.IsFrozenClinicProviderGen.INSTANCE; } @TruffleBoundary @Specialization boolean run(TruffleString name) { return findFrozen(getContext(), name).status == FROZEN_OKAY; } } @Builtin(name = "is_frozen_package", parameterNames = {"name"}, minNumOfPositionalArgs = 1, doc = "is_frozen_package($module, name, /)\n" + "--\n" + "\n" + "Returns True if the module name is of a frozen package.") @GenerateNodeFactory @ArgumentClinic(name = "name", conversion = ArgumentClinic.ClinicConversion.TString) abstract static class IsFrozenPackage extends PythonUnaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.IsFrozenClinicProviderGen.INSTANCE; } @TruffleBoundary @Specialization static boolean run(TruffleString name, @Bind PythonContext context) { FrozenResult result = findFrozen(context, name); if (result.status != FROZEN_EXCLUDED) { raiseFrozenError(result.status, name); } return result.info.isPackage; } } @Builtin(name = "get_frozen_object", parameterNames = {"name", "data"}, minNumOfPositionalArgs = 1, doc = "get_frozen_object($module, name, data=None, /)\n" + "--\n" + "\n" + "Create a code object for a frozen module.") @GenerateNodeFactory @ArgumentClinic(name = "name", conversion = ArgumentClinic.ClinicConversion.TString) @ArgumentClinic(name = "data", conversion = ClinicConversion.ReadableBuffer, defaultValue = "PNone.NONE", useDefaultForNone = true) abstract static class GetFrozenObject extends PythonBinaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.GetFrozenObjectClinicProviderGen.INSTANCE; } @TruffleBoundary @Specialization static Object run(TruffleString name, Object dataObj, @Bind Node inliningTarget, @Bind PythonContext context) { FrozenInfo info; if (dataObj != PNone.NONE) { byte[] bytes; int size; PythonBufferAccessLibrary bufferLib = PythonBufferAccessLibrary.getUncached(); try { bytes = bufferLib.getInternalOrCopiedByteArray(dataObj); size = bufferLib.getBufferLength(dataObj); } finally { bufferLib.release(dataObj); } if (size == 0) { /* Does not contain executable code. */ raiseFrozenError(FROZEN_INVALID, name); } Object code = null; try { code = MarshalModuleBuiltins.Marshal.load(context, bytes, size); } catch (MarshalError | NumberFormatException e) { raiseFrozenError(FROZEN_INVALID, name); } if (!(code instanceof PCode)) { throw PRaiseNode.raiseStatic(inliningTarget, TypeError, ErrorMessages.NOT_A_CODE_OBJECT, name); } return code; } else { FrozenResult result = findFrozen(context, name); FrozenStatus status = result.status; info = result.info; raiseFrozenError(status, name); RootCallTarget callTarget = createCallTarget(context, info); return PFactory.createCode(context.getLanguage(), callTarget); } } } @Builtin(name = "find_frozen", parameterNames = {"name", "withdata"}, minNumOfPositionalArgs = 1, doc = "find_frozen($module, name, /, *, withdata=False)\n" + "--\n" + "\n" + "Return info about the corresponding frozen module (if there is one) or None.\n" + "\n" + "The returned info (a 3-tuple):\n" + "\n" + " * data the raw marshalled bytes\n" + " * is_package whether or not it is a package\n" + " * origname the originally frozen module\'s name, or None if not\n" + " a stdlib module (this will usually be the same as\n" + " the module\'s current name)") @GenerateNodeFactory @ArgumentClinic(name = "name", conversion = ArgumentClinic.ClinicConversion.TString) @ArgumentClinic(name = "withdata", conversion = ArgumentClinic.ClinicConversion.Boolean, defaultValue = "false", useDefaultForNone = true) abstract static class FindFrozen extends PythonBinaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.FindFrozenClinicProviderGen.INSTANCE; } @TruffleBoundary @Specialization static Object run(TruffleString name, boolean withData, @Bind Node inliningTarget, @Bind PythonContext context) { FrozenResult result = findFrozen(context, name); FrozenStatus status = result.status; FrozenInfo info = result.info; switch (status) { case FROZEN_NOT_FOUND: case FROZEN_DISABLED: case FROZEN_BAD_NAME: return PNone.NONE; default: raiseFrozenError(status, name); } PMemoryView data = null; if (withData) { byte[] bytes = MarshalModuleBuiltins.serializeCodeUnit(inliningTarget, context, info.code); data = PyMemoryViewFromObject.getUncached().execute(null, PFactory.createBytes(context.getLanguage(inliningTarget), bytes)); } Object[] returnValues = new Object[]{ data == null ? PNone.NONE : data, info.isPackage, info.origName == null ? PNone.NONE : info.origName }; return PFactory.createTuple(context.getLanguage(inliningTarget), returnValues); } } @Builtin(name = "init_frozen", parameterNames = {"name"}, minNumOfPositionalArgs = 1, doc = "init_frozen($module, name, /)\n" + "--\n" + "\n" + "Initializes a frozen module.") @GenerateNodeFactory @ArgumentClinic(name = "name", conversion = ArgumentClinic.ClinicConversion.TString) abstract static class InitFrozen extends PythonUnaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.InitFrozenClinicProviderGen.INSTANCE; } @Specialization @TruffleBoundary static PythonModule run(TruffleString name, @Bind PythonContext context) { return importFrozenModuleObject(context, name, true); } } /** * Equivalent to CPythons PyImport_FrozenModuleObject. Initialize a frozen module. Returns the * imported module, null, or raises a Python exception. */ @TruffleBoundary public static PythonModule importFrozenModuleObject(Python3Core core, TruffleString name, boolean doRaise) { return importFrozenModuleObject(core, name, doRaise, null); } /** * @see #importFrozenModuleObject * * Uses {@code globals} if given as the globals for execution. */ @TruffleBoundary public static PythonModule importFrozenModuleObject(Python3Core core, TruffleString name, boolean doRaise, PythonModule globals) { FrozenResult result = findFrozen(core.getContext(), name); FrozenStatus status = result.status; FrozenInfo info = result.info; switch (status) { case FROZEN_NOT_FOUND: case FROZEN_DISABLED: case FROZEN_BAD_NAME: return null; default: if (doRaise) { raiseFrozenError(status, name); } else if (status != FROZEN_OKAY) { return null; } } RootCallTarget callTarget = createCallTarget(core.getContext(), info); PythonModule module = globals == null ? PFactory.createPythonModule(core.getLanguage(), name) : globals; if (info.isPackage) { /* Set __path__ to the empty list */ WriteAttributeToPythonObjectNode.getUncached().execute(module, T___PATH__, PFactory.createList(core.getLanguage())); } CallDispatchers.SimpleIndirectInvokeNode.executeUncached(callTarget, PArguments.withGlobals(module)); Object origName = info.origName == null ? PNone.NONE : info.origName; WriteAttributeToPythonObjectNode.getUncached().execute(module, T___ORIGNAME__, origName); return module; } private static RootCallTarget createCallTarget(PythonContext context, FrozenInfo info) { String name = PythonLanguage.FROZEN_FILENAME_PREFIX + info.name + PythonLanguage.FROZEN_FILENAME_SUFFIX; Source source = Source.newBuilder("python", "", name).content(Source.CONTENT_NONE).build(); return context.getLanguage().callTargetFromBytecode(context, source, info.code); } /* * CPython's version of this accepts any object and casts, but all Python-level callers use * argument clinic to convert the name first. The only exception is * PyImport_ImportFrozenModuleObject, which we don't expose as C API and handle differently_ */ private static FrozenResult findFrozen(PythonContext context, TruffleString name) { TriState override = context.getOverrideFrozenModules(); if (override == TriState.FALSE || (override == TriState.UNDEFINED && context.getOption(PythonOptions.DisableFrozenModules))) { return new FrozenResult(FROZEN_DISABLED); } PythonFrozenModule module = FrozenModules.lookup(name.toJavaStringUncached()); if (module == null) { return new FrozenResult(FROZEN_NOT_FOUND); } boolean isAlias = module.getOriginalName() == null || !name.equalsUncached(module.getOriginalName(), TS_ENCODING); FrozenInfo info = new FrozenInfo(name, module.getCode(), module.isPackage(), module.getOriginalName(), !isAlias); if (info.code == null) { return new FrozenResult(FROZEN_INVALID, info); } return new FrozenResult(FROZEN_OKAY, info); } private static void raiseFrozenError(FrozenStatus status, TruffleString moduleName) { if (status == FROZEN_OKAY) { // There was no error. return; } TruffleString message = switch (status) { case FROZEN_BAD_NAME, FROZEN_NOT_FOUND -> ErrorMessages.NO_SUCH_FROZEN_OBJECT; case FROZEN_DISABLED -> ErrorMessages.FROZEN_DISABLED; case FROZEN_EXCLUDED -> ErrorMessages.FROZEN_EXCLUDED; case FROZEN_INVALID -> ErrorMessages.FROZEN_INVALID; default -> throw CompilerDirectives.shouldNotReachHere("unknown frozen status"); }; throw PConstructAndRaiseNode.getUncached().raiseImportErrorWithModule(null, moduleName, PNone.NONE, message, moduleName); } @Builtin(name = "source_hash", minNumOfPositionalArgs = 2, parameterNames = {"key", "source"}) @ArgumentClinic(name = "key", conversion = ArgumentClinic.ClinicConversion.Long) @ArgumentClinic(name = "source", conversion = ArgumentClinic.ClinicConversion.ReadableBuffer) @GenerateNodeFactory public abstract static class SourceHashNode extends PythonBinaryClinicBuiltinNode { @TruffleBoundary @Specialization static PBytes run(long magicNumber, Object sourceBuffer, @Bind PythonLanguage language) { long sourceHash = BytesNodes.HashBufferNode.executeUncached(sourceBuffer); return PFactory.createBytes(language, computeHash(magicNumber, sourceHash)); } @TruffleBoundary private static byte[] computeHash(long magicNumber, long sourceHash) { byte[] hash = new byte[Long.BYTES]; long hashCode = magicNumber ^ sourceHash; for (int i = 0; i < hash.length; i++) { hash[i] = (byte) (hashCode << (8 * i)); } return hash; } @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.SourceHashNodeClinicProviderGen.INSTANCE; } } @Builtin(name = "_fix_co_filename", minNumOfPositionalArgs = 2) @GenerateNodeFactory public abstract static class FixCoFilename extends PythonBinaryBuiltinNode { @Specialization @TruffleBoundary public Object run(PCode code, PString path, @Bind Node inliningTarget, @Cached CastToTruffleStringNode castToStringNode) { code.setFilename(castToStringNode.execute(inliningTarget, path)); return PNone.NONE; } @Specialization @TruffleBoundary public Object run(PCode code, TruffleString path) { code.setFilename(path); return PNone.NONE; } } @Builtin(name = "extension_suffixes") @GenerateNodeFactory public abstract static class ExtensionSuffixesNode extends PythonBuiltinNode { @Specialization Object run( @Bind PythonLanguage language) { return PFactory.createList(language, new Object[]{PythonContext.get(this).getSoAbi(), T_EXT_SO, T_EXT_PYD}); } } @Builtin(name = "create_dynamic", minNumOfPositionalArgs = 1, parameterNames = {"spec", "file"}) @GenerateNodeFactory public abstract static class CreateDynamicNode extends PythonBinaryBuiltinNode { @Specialization static Object run(VirtualFrame frame, PythonObject moduleSpec, @SuppressWarnings("unused") Object fileName, @Bind Node inliningTarget, @Bind PythonContext context, @Cached("createFor($node)") IndirectCallData indirectCallData) { PythonLanguage language = context.getLanguage(inliningTarget); Object state = IndirectCallContext.enter(frame, language, context, indirectCallData); try { return doCreate(moduleSpec, inliningTarget, context); } finally { IndirectCallContext.exit(frame, language, context, state); } } @TruffleBoundary private static Object doCreate(PythonObject moduleSpec, Node inliningTarget, PythonContext context) { try { TruffleString name = CastToTruffleStringNode.executeUncached(PyObjectGetAttr.executeUncached(moduleSpec, T_NAME)); TruffleString path = CastToTruffleStringNode.executeUncached(PyObjectGetAttr.executeUncached(moduleSpec, T_ORIGIN)); ModuleSpec spec = new ModuleSpec(name, path, moduleSpec); CApiContext cApiContext = context.getCApiContext(); if (cApiContext != null) { // TODO check m_size // TODO populate m_copy? PythonModule existingModule = cApiContext.findExtension(spec.path, spec.name); if (existingModule != null) { return existingModule; } } TruffleString oldPackageContext = context.getPyPackageContext(); context.setPyPackageContext(name); try { return CApiContext.loadCExtModule(inliningTarget, context, spec); } finally { context.setPyPackageContext(oldPackageContext); } } catch (CannotCastException e) { throw PRaiseNode.raiseStatic(inliningTarget, TypeError, ErrorMessages.BAD_ARG_TYPE_FOR_BUILTIN_OP); } catch (ApiInitException ie) { throw ie.reraise(); } catch (ImportException ie) { throw ie.reraise(); } catch (IOException e) { throw PConstructAndRaiseNode.getUncached().raiseOSError(null, e, TruffleString.EqualNode.getUncached()); } } } @Builtin(name = "_override_frozen_modules_for_tests", minNumOfPositionalArgs = 1, parameterNames = {"override"}) @ArgumentClinic(name = "override", conversion = ClinicConversion.Int) @GenerateNodeFactory abstract static class OverrideFrozenModulesForTests extends PythonUnaryClinicBuiltinNode { @Specialization @TruffleBoundary Object set(int override) { TriState value = TriState.UNDEFINED; if (override > 0) { value = TriState.TRUE; } else if (override < 0) { value = TriState.FALSE; } PythonContext.get(null).setOverrideFrozenModules(value); return PNone.NONE; } @Override protected ArgumentClinicProvider getArgumentClinic() { return ImpModuleBuiltinsClinicProviders.OverrideFrozenModulesForTestsClinicProviderGen.INSTANCE; } } }
apache/httpcomponents-client
36,463
httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestRedirects.java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.hc.client5.testing.sync; import static org.hamcrest.MatcherAssert.assertThat; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.URI; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collections; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; import org.apache.hc.client5.http.CircularRedirectException; import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc.client5.http.RedirectException; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.cookie.BasicCookieStore; import org.apache.hc.client5.http.cookie.CookieStore; import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy; import org.apache.hc.client5.http.impl.LaxRedirectStrategy; import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.protocol.RedirectLocations; import org.apache.hc.client5.testing.OldPathRedirectResolver; import org.apache.hc.client5.testing.classic.EchoHandler; import org.apache.hc.client5.testing.classic.RandomHandler; import org.apache.hc.client5.testing.classic.RedirectingDecorator; import org.apache.hc.client5.testing.extension.sync.ClientProtocolLevel; import org.apache.hc.client5.testing.extension.sync.TestClient; import org.apache.hc.client5.testing.extension.sync.TestServer; import org.apache.hc.client5.testing.extension.sync.TestServerBootstrap; import org.apache.hc.client5.testing.redirect.Redirect; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ConnectionClosedException; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHeaders; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.ProtocolException; import org.apache.hc.core5.http.URIScheme; import org.apache.hc.core5.http.io.HttpRequestHandler; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.hc.core5.http.message.BasicHeader; import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.io.CloseMode; import org.apache.hc.core5.net.URIBuilder; import org.apache.hc.core5.util.TimeValue; import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Redirection test cases. */ abstract class TestRedirects extends AbstractIntegrationTestBase { protected TestRedirects(final URIScheme scheme) { super(scheme, ClientProtocolLevel.STANDARD); } @Test void testBasicRedirect300() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES))) .register("/random/*", new RandomHandler()) ); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/100"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(), reqWrapper.getUri()); final RedirectLocations redirects = context.getRedirectLocations(); Assertions.assertNotNull(redirects); Assertions.assertEquals(0, redirects.size()); } @Test void testBasicRedirect300NoKeepAlive() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MULTIPLE_CHOICES, Redirect.ConnControl.CLOSE))) .register("/random/*", new RandomHandler()) ); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/100"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_MULTIPLE_CHOICES, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/100").build(), reqWrapper.getUri()); final RedirectLocations redirects = context.getRedirectLocations(); Assertions.assertNotNull(redirects); Assertions.assertEquals(0, redirects.size()); } @Test void testBasicRedirect301() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_PERMANENTLY))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/100"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(), reqWrapper.getUri()); final RedirectLocations redirects = context.getRedirectLocations(); Assertions.assertNotNull(redirects); Assertions.assertEquals(1, redirects.size()); final URI redirect = new URIBuilder().setHttpHost(target).setPath("/random/100").build(); Assertions.assertTrue(redirects.contains(redirect)); } @Test void testBasicRedirect302() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/50"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/50").build(), reqWrapper.getUri()); } @Test void testBasicRedirect302NoLocation() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, requestUri -> { final String path = requestUri.getPath(); if (path.startsWith("/oldlocation")) { return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, null); } return null; })) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/100"); client.execute(target, httpget, context, response -> { final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode()); Assertions.assertEquals("/oldlocation/100", reqWrapper.getRequestUri()); EntityUtils.consume(response.getEntity()); return null; }); } @Test void testBasicRedirect303() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_SEE_OTHER))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/123"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(), reqWrapper.getUri()); } @Test void testBasicRedirect304() throws Exception { configureServer(bootstrap -> bootstrap .register("/oldlocation/*", (request, response, context) -> { response.setCode(HttpStatus.SC_NOT_MODIFIED); response.addHeader(HttpHeaders.LOCATION, "/random/100"); }) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/stuff"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(), reqWrapper.getUri()); final RedirectLocations redirects = context.getRedirectLocations(); Assertions.assertNotNull(redirects); Assertions.assertEquals(0, redirects.size()); } @Test void testBasicRedirect305() throws Exception { configureServer(bootstrap -> bootstrap .register("/oldlocation/*", (request, response, context) -> { response.setCode(HttpStatus.SC_USE_PROXY); response.addHeader(HttpHeaders.LOCATION, "/random/100"); }) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/stuff"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_USE_PROXY, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/oldlocation/stuff").build(), reqWrapper.getUri()); final RedirectLocations redirects = context.getRedirectLocations(); Assertions.assertNotNull(redirects); Assertions.assertEquals(0, redirects.size()); } @Test void testBasicRedirect307() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_TEMPORARY_REDIRECT))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/123"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/123").build(), reqWrapper.getUri()); } @Test void testMaxRedirectCheck() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/circular-oldlocation/", "/circular-oldlocation/", HttpStatus.SC_MOVED_TEMPORARILY))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final RequestConfig config = RequestConfig.custom() .setCircularRedirectsAllowed(true) .setMaxRedirects(5) .build(); final HttpGet httpget = new HttpGet("/circular-oldlocation/123"); httpget.setConfig(config); final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () -> client.execute(target, httpget, response -> null)); Assertions.assertTrue(exception.getCause() instanceof RedirectException); } @Test void testCircularRedirect() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/circular-oldlocation/", "/circular-oldlocation/", HttpStatus.SC_MOVED_TEMPORARILY))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final RequestConfig config = RequestConfig.custom() .setCircularRedirectsAllowed(false) .build(); final HttpGet httpget = new HttpGet("/circular-oldlocation/123"); httpget.setConfig(config); final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () -> client.execute(target, httpget, response -> null)); Assertions.assertTrue(exception.getCause() instanceof CircularRedirectException); } @Test void testPostRedirectSeeOther() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/echo", HttpStatus.SC_SEE_OTHER))) .register("/echo/*", new EchoHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpPost httppost = new HttpPost("/oldlocation/stuff"); httppost.setEntity(new StringEntity("stuff")); client.execute(target, httppost, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/echo/stuff").build(), reqWrapper.getUri()); Assertions.assertEquals("GET", reqWrapper.getMethod()); } @Test void testRelativeRedirect() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, requestUri -> { final String path = requestUri.getPath(); if (path.startsWith("/oldlocation")) { return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "/random/100"); } return null; })) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/stuff"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(), reqWrapper.getUri()); } @Test void testRelativeRedirect2() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, requestUri -> { final String path = requestUri.getPath(); if (path.equals("/random/oldlocation")) { return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "100"); } return null; })) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/random/oldlocation"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(), reqWrapper.getUri()); } @Test void testRejectBogusRedirectLocation() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, requestUri -> { final String path = requestUri.getPath(); if (path.equals("/oldlocation")) { return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "xxx://bogus"); } return null; })) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpGet httpget = new HttpGet("/oldlocation"); final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () -> client.execute(target, httpget, response -> null)); assertThat(exception.getCause(), CoreMatchers.instanceOf(HttpException.class)); } @Test void testRejectInvalidRedirectLocation() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, requestUri -> { final String path = requestUri.getPath(); if (path.equals("/oldlocation")) { return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, "/newlocation/?p=I have spaces"); } return null; })) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpGet httpget = new HttpGet("/oldlocation"); final ClientProtocolException exception = Assertions.assertThrows(ClientProtocolException.class, () -> client.execute(target, httpget, response -> null)); assertThat(exception.getCause(), CoreMatchers.instanceOf(ProtocolException.class)); } @Test void testRedirectWithCookie() throws Exception { configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setDomain(target.getHostName()); cookie.setPath("/"); cookieStore.addCookie(cookie); final HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); final HttpGet httpget = new HttpGet("/oldlocation/100"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(), reqWrapper.getUri()); final Header[] headers = reqWrapper.getHeaders("Cookie"); Assertions.assertEquals(1, headers.length, "There can only be one (cookie)"); } @Test void testDefaultHeadersRedirect() throws Exception { configureClient(builder -> builder .setDefaultHeaders(Collections.singletonList(new BasicHeader(HttpHeaders.USER_AGENT, "my-test-client"))) ); configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY))) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/100"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(), reqWrapper.getUri()); final Header header = reqWrapper.getFirstHeader(HttpHeaders.USER_AGENT); Assertions.assertEquals("my-test-client", header.getValue()); } @Test void testCompressionHeaderRedirect() throws Exception { final Queue<String> values = new ConcurrentLinkedQueue<>(); configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY)) { @Override public void handle(final ClassicHttpRequest request, final ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException { final Header header = request.getHeader(HttpHeaders.ACCEPT_ENCODING); if (header != null) { values.add(header.getValue()); } super.handle(request, responseTrigger, context); } }) .register("/random/*", new RandomHandler())); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/100"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder().setHttpHost(target).setPath("/random/100").build(), reqWrapper.getUri()); assertThat(values.poll(), CoreMatchers.equalTo("gzip, deflate, lz4-framed, lz4-block, bzip2, pack200, deflate64, x-gzip")); assertThat(values.poll(), CoreMatchers.equalTo("gzip, deflate, lz4-framed, lz4-block, bzip2, pack200, deflate64, x-gzip")); assertThat(values.poll(), CoreMatchers.nullValue()); } @Test void testRetryUponRedirect() throws Exception { configureClient(builder -> builder .setRetryStrategy(new DefaultHttpRequestRetryStrategy( 3, TimeValue.ofSeconds(1), Arrays.asList( InterruptedIOException.class, UnknownHostException.class, ConnectException.class, ConnectionClosedException.class, NoRouteToHostException.class), Arrays.asList( HttpStatus.SC_TOO_MANY_REQUESTS, HttpStatus.SC_SERVICE_UNAVAILABLE)) { }) ); configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, new OldPathRedirectResolver("/oldlocation", "/random", HttpStatus.SC_MOVED_TEMPORARILY))) .register("/random/*", new HttpRequestHandler() { final AtomicLong count = new AtomicLong(); @Override public void handle(final ClassicHttpRequest request, final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { if (count.incrementAndGet() == 1) { throw new IOException("Boom"); } response.setCode(200); response.setEntity(new StringEntity("test")); } })); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/oldlocation/50"); client.execute(target, httpget, context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final HttpRequest reqWrapper = context.getRequest(); Assertions.assertEquals(new URIBuilder() .setHttpHost(target) .setPath("/random/50") .build(), reqWrapper.getUri()); } @ParameterizedTest(name = "{displayName}; manually added header: {0}") @ValueSource(strings = {HttpHeaders.AUTHORIZATION, HttpHeaders.COOKIE}) void testCrossSiteRedirectWithSensitiveHeaders(final String headerName) throws Exception { final URIScheme scheme = scheme(); final TestServer secondServer = new TestServerBootstrap(scheme()) .register("/random/*", new RandomHandler()) .build(); try { final InetSocketAddress address2 = secondServer.start(); final HttpHost redirectTarget = new HttpHost(scheme.name(), "localhost", address2.getPort()); configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, requestUri -> { final URI location = new URIBuilder(requestUri) .setHttpHost(redirectTarget) .setPath("/random/100") .build(); return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, location.toString()); })) .register("/random/*", new RandomHandler()) ); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); client.execute(target, ClassicRequestBuilder.get() .setHttpHost(target) .setPath("/oldlocation") .setHeader(headerName, "custom header") .build(), context, response -> { Assertions.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final RedirectLocations redirects = context.getRedirectLocations(); Assertions.assertNotNull(redirects); Assertions.assertEquals(0, redirects.size()); } finally { secondServer.shutdown(CloseMode.GRACEFUL); } } @ParameterizedTest(name = "{displayName}; manually added header: {0}") @ValueSource(strings = {HttpHeaders.AUTHORIZATION, HttpHeaders.COOKIE}) void testCrossSiteRedirectWithSensitiveHeadersAndLaxRedirectStrategy(final String headerName) throws Exception { configureClient(builder -> builder .setRedirectStrategy(new LaxRedirectStrategy()) ); final URIScheme scheme = scheme(); final TestServer secondServer = new TestServerBootstrap(scheme()) .register("/random/*", new RandomHandler()) .build(); try { final InetSocketAddress address2 = secondServer.start(); final HttpHost redirectTarget = new HttpHost(scheme.name(), "localhost", address2.getPort()); configureServer(bootstrap -> bootstrap .setExchangeHandlerDecorator(requestHandler -> new RedirectingDecorator( requestHandler, requestUri -> { final URI location = new URIBuilder(requestUri) .setHttpHost(redirectTarget) .setPath("/random/100") .build(); return new Redirect(HttpStatus.SC_MOVED_TEMPORARILY, location.toString()); })) .register("/random/*", new RandomHandler()) ); final HttpHost target = startServer(); final TestClient client = client(); final HttpClientContext context = HttpClientContext.create(); client.execute(target, ClassicRequestBuilder.get() .setHttpHost(target) .setPath("/oldlocation") .setHeader(headerName, "custom header") .build(), context, response -> { Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); EntityUtils.consume(response.getEntity()); return null; }); final RedirectLocations redirects = context.getRedirectLocations(); Assertions.assertNotNull(redirects); Assertions.assertEquals(1, redirects.size()); } finally { secondServer.shutdown(CloseMode.GRACEFUL); } } }
googleapis/google-cloud-java
36,300
java-cloudsupport/proto-google-cloud-cloudsupport-v2/src/main/java/com/google/cloud/support/v2/SearchCasesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/support/v2/case_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.support.v2; /** * * * <pre> * The response message for the SearchCases endpoint. * </pre> * * Protobuf type {@code google.cloud.support.v2.SearchCasesResponse} */ public final class SearchCasesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.support.v2.SearchCasesResponse) SearchCasesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use SearchCasesResponse.newBuilder() to construct. private SearchCasesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SearchCasesResponse() { cases_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SearchCasesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.support.v2.CaseServiceProto .internal_static_google_cloud_support_v2_SearchCasesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.support.v2.CaseServiceProto .internal_static_google_cloud_support_v2_SearchCasesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.support.v2.SearchCasesResponse.class, com.google.cloud.support.v2.SearchCasesResponse.Builder.class); } public static final int CASES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.support.v2.Case> cases_; /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.support.v2.Case> getCasesList() { return cases_; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.support.v2.CaseOrBuilder> getCasesOrBuilderList() { return cases_; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ @java.lang.Override public int getCasesCount() { return cases_.size(); } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ @java.lang.Override public com.google.cloud.support.v2.Case getCases(int index) { return cases_.get(index); } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ @java.lang.Override public com.google.cloud.support.v2.CaseOrBuilder getCasesOrBuilder(int index) { return cases_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. Set this in the * `page_token` field of subsequent `cases.search` requests. If unspecified, * there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve the next page of results. Set this in the * `page_token` field of subsequent `cases.search` requests. If unspecified, * there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < cases_.size(); i++) { output.writeMessage(1, cases_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < cases_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, cases_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.support.v2.SearchCasesResponse)) { return super.equals(obj); } com.google.cloud.support.v2.SearchCasesResponse other = (com.google.cloud.support.v2.SearchCasesResponse) obj; if (!getCasesList().equals(other.getCasesList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getCasesCount() > 0) { hash = (37 * hash) + CASES_FIELD_NUMBER; hash = (53 * hash) + getCasesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.support.v2.SearchCasesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.support.v2.SearchCasesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.support.v2.SearchCasesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.support.v2.SearchCasesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response message for the SearchCases endpoint. * </pre> * * Protobuf type {@code google.cloud.support.v2.SearchCasesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.support.v2.SearchCasesResponse) com.google.cloud.support.v2.SearchCasesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.support.v2.CaseServiceProto .internal_static_google_cloud_support_v2_SearchCasesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.support.v2.CaseServiceProto .internal_static_google_cloud_support_v2_SearchCasesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.support.v2.SearchCasesResponse.class, com.google.cloud.support.v2.SearchCasesResponse.Builder.class); } // Construct using com.google.cloud.support.v2.SearchCasesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (casesBuilder_ == null) { cases_ = java.util.Collections.emptyList(); } else { cases_ = null; casesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.support.v2.CaseServiceProto .internal_static_google_cloud_support_v2_SearchCasesResponse_descriptor; } @java.lang.Override public com.google.cloud.support.v2.SearchCasesResponse getDefaultInstanceForType() { return com.google.cloud.support.v2.SearchCasesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.support.v2.SearchCasesResponse build() { com.google.cloud.support.v2.SearchCasesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.support.v2.SearchCasesResponse buildPartial() { com.google.cloud.support.v2.SearchCasesResponse result = new com.google.cloud.support.v2.SearchCasesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.support.v2.SearchCasesResponse result) { if (casesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { cases_ = java.util.Collections.unmodifiableList(cases_); bitField0_ = (bitField0_ & ~0x00000001); } result.cases_ = cases_; } else { result.cases_ = casesBuilder_.build(); } } private void buildPartial0(com.google.cloud.support.v2.SearchCasesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.support.v2.SearchCasesResponse) { return mergeFrom((com.google.cloud.support.v2.SearchCasesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.support.v2.SearchCasesResponse other) { if (other == com.google.cloud.support.v2.SearchCasesResponse.getDefaultInstance()) return this; if (casesBuilder_ == null) { if (!other.cases_.isEmpty()) { if (cases_.isEmpty()) { cases_ = other.cases_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureCasesIsMutable(); cases_.addAll(other.cases_); } onChanged(); } } else { if (!other.cases_.isEmpty()) { if (casesBuilder_.isEmpty()) { casesBuilder_.dispose(); casesBuilder_ = null; cases_ = other.cases_; bitField0_ = (bitField0_ & ~0x00000001); casesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCasesFieldBuilder() : null; } else { casesBuilder_.addAllMessages(other.cases_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.support.v2.Case m = input.readMessage(com.google.cloud.support.v2.Case.parser(), extensionRegistry); if (casesBuilder_ == null) { ensureCasesIsMutable(); cases_.add(m); } else { casesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.support.v2.Case> cases_ = java.util.Collections.emptyList(); private void ensureCasesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { cases_ = new java.util.ArrayList<com.google.cloud.support.v2.Case>(cases_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.support.v2.Case, com.google.cloud.support.v2.Case.Builder, com.google.cloud.support.v2.CaseOrBuilder> casesBuilder_; /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public java.util.List<com.google.cloud.support.v2.Case> getCasesList() { if (casesBuilder_ == null) { return java.util.Collections.unmodifiableList(cases_); } else { return casesBuilder_.getMessageList(); } } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public int getCasesCount() { if (casesBuilder_ == null) { return cases_.size(); } else { return casesBuilder_.getCount(); } } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public com.google.cloud.support.v2.Case getCases(int index) { if (casesBuilder_ == null) { return cases_.get(index); } else { return casesBuilder_.getMessage(index); } } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder setCases(int index, com.google.cloud.support.v2.Case value) { if (casesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCasesIsMutable(); cases_.set(index, value); onChanged(); } else { casesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder setCases(int index, com.google.cloud.support.v2.Case.Builder builderForValue) { if (casesBuilder_ == null) { ensureCasesIsMutable(); cases_.set(index, builderForValue.build()); onChanged(); } else { casesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder addCases(com.google.cloud.support.v2.Case value) { if (casesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCasesIsMutable(); cases_.add(value); onChanged(); } else { casesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder addCases(int index, com.google.cloud.support.v2.Case value) { if (casesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCasesIsMutable(); cases_.add(index, value); onChanged(); } else { casesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder addCases(com.google.cloud.support.v2.Case.Builder builderForValue) { if (casesBuilder_ == null) { ensureCasesIsMutable(); cases_.add(builderForValue.build()); onChanged(); } else { casesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder addCases(int index, com.google.cloud.support.v2.Case.Builder builderForValue) { if (casesBuilder_ == null) { ensureCasesIsMutable(); cases_.add(index, builderForValue.build()); onChanged(); } else { casesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder addAllCases( java.lang.Iterable<? extends com.google.cloud.support.v2.Case> values) { if (casesBuilder_ == null) { ensureCasesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, cases_); onChanged(); } else { casesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder clearCases() { if (casesBuilder_ == null) { cases_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { casesBuilder_.clear(); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public Builder removeCases(int index) { if (casesBuilder_ == null) { ensureCasesIsMutable(); cases_.remove(index); onChanged(); } else { casesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public com.google.cloud.support.v2.Case.Builder getCasesBuilder(int index) { return getCasesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public com.google.cloud.support.v2.CaseOrBuilder getCasesOrBuilder(int index) { if (casesBuilder_ == null) { return cases_.get(index); } else { return casesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public java.util.List<? extends com.google.cloud.support.v2.CaseOrBuilder> getCasesOrBuilderList() { if (casesBuilder_ != null) { return casesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(cases_); } } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public com.google.cloud.support.v2.Case.Builder addCasesBuilder() { return getCasesFieldBuilder() .addBuilder(com.google.cloud.support.v2.Case.getDefaultInstance()); } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public com.google.cloud.support.v2.Case.Builder addCasesBuilder(int index) { return getCasesFieldBuilder() .addBuilder(index, com.google.cloud.support.v2.Case.getDefaultInstance()); } /** * * * <pre> * The list of cases associated with the parent after any * filters have been applied. * </pre> * * <code>repeated .google.cloud.support.v2.Case cases = 1;</code> */ public java.util.List<com.google.cloud.support.v2.Case.Builder> getCasesBuilderList() { return getCasesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.support.v2.Case, com.google.cloud.support.v2.Case.Builder, com.google.cloud.support.v2.CaseOrBuilder> getCasesFieldBuilder() { if (casesBuilder_ == null) { casesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.support.v2.Case, com.google.cloud.support.v2.Case.Builder, com.google.cloud.support.v2.CaseOrBuilder>( cases_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); cases_ = null; } return casesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. Set this in the * `page_token` field of subsequent `cases.search` requests. If unspecified, * there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve the next page of results. Set this in the * `page_token` field of subsequent `cases.search` requests. If unspecified, * there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve the next page of results. Set this in the * `page_token` field of subsequent `cases.search` requests. If unspecified, * there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve the next page of results. Set this in the * `page_token` field of subsequent `cases.search` requests. If unspecified, * there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve the next page of results. Set this in the * `page_token` field of subsequent `cases.search` requests. If unspecified, * there are no more results to retrieve. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.support.v2.SearchCasesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.support.v2.SearchCasesResponse) private static final com.google.cloud.support.v2.SearchCasesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.support.v2.SearchCasesResponse(); } public static com.google.cloud.support.v2.SearchCasesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SearchCasesResponse> PARSER = new com.google.protobuf.AbstractParser<SearchCasesResponse>() { @java.lang.Override public SearchCasesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SearchCasesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SearchCasesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.support.v2.SearchCasesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/blockly-android
36,422
blocklylib-core/src/main/java/com/google/blockly/model/BlockFactory.java
/* * Copyright 2015 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.blockly.model; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; import android.util.Log; import com.google.blockly.android.control.BlocklyController; import com.google.blockly.utils.BlockLoadingException; import com.google.blockly.utils.BlocklyXmlHelper; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.UUID; /** * The BlockFactory is responsible for managing the set of BlockDefinitions, and instantiating * {@link Block}s from those definitions. * * Add new definitions to the factory via {@link #addJsonDefinitions}. Create new Blocks by calling * {@link #obtainBlockFrom(BlockTemplate)}. Using {@link BlockTemplate}'s chaining methods, this * can look like: * * <pre>{@code * // Add definition. * factory.addJsonDefinitions(getAssets().open("default/math_blocks.json")); * // Create blocks. * Block pi = factory.obtainBlockFrom(new BlockTemplate().ofType("math_number").withId("PI")); * factory.obtainBlockFrom(new BlockTemplate().copyOf(pi).shadow().withId("PI-shadow")); * }</pre> */ public class BlockFactory { private static final String TAG = "BlockFactory"; private final Map<String, BlockDefinition> mDefinitions = new HashMap<>(); private final Map<String, Mutator.Factory> mMutatorFactories = new HashMap<>(); private final Map<String, BlockExtension> mExtensions = new HashMap<>(); private final Map<String, WeakReference<Block>> mBlockRefs = new HashMap<>(); protected BlocklyController mController; /** * The global list of dropdown options available to each field matching the * {@link BlockTypeFieldName} key. */ protected final HashMap<BlockTypeFieldName, WeakReference<FieldDropdown.Options>> mDropdownOptions = new HashMap<>(); /** Default constructor. */ public BlockFactory() { } public void setController(BlocklyController controller) { if (mController != null && controller != mController) { throw new IllegalStateException( "BlockFactory is already associated with another BlocklyController."); } mController = controller; } /** * @param id The id to check. * @returns True if a block with the given id exists. Otherwise, false. */ public boolean isBlockIdInUse(String id) { WeakReference<Block> priorBlockRef = mBlockRefs.get(id); return priorBlockRef != null && priorBlockRef.get() != null; } /** * Registers a new BlockDefinition with the factory. * @param definition The new definition. * @throws IllegalArgumentException If type name is already defined. */ public void addDefinition(BlockDefinition definition) { String typeName = definition.getTypeName(); if (mDefinitions.containsKey(typeName)) { throw new IllegalArgumentException( "Definition \"" + typeName + "\" already defined. Prior must remove first."); } mDefinitions.put(typeName, definition); } /** * Loads and adds block definitions from a JSON array in an input stream. * * @param jsonStream The stream containing the JSON block definitions. * * @return A count of definitions added. * @throws IOException If there is a fundamental problem with the input. * @throws BlockLoadingException If the definition is malformed. */ public int addJsonDefinitions(InputStream jsonStream) throws IOException, BlockLoadingException { // Read stream as single string. String inString = new Scanner( jsonStream ).useDelimiter("\\A").next(); return addJsonDefinitions(inString); } /** * Loads and adds block definition from a JSON array string. These definitions will replace * existing definitions, if the type names conflict. * * @param jsonString The InputStream containing the JSON block definitions. * * @return A count of definitions added. * @throws IOException If there is a fundamental problem with the input. * @throws BlockLoadingException If the definition is malformed. */ public int addJsonDefinitions(String jsonString) throws IOException, BlockLoadingException { // Parse JSON first, avoiding side effects (partially added file) in the case of an error. List<BlockDefinition> defs; int arrayIndex = 0; // definition index try { JSONArray jsonArray = new JSONArray(jsonString); defs = new ArrayList<>(jsonArray.length()); for (arrayIndex = 0; arrayIndex < jsonArray.length(); arrayIndex++) { JSONObject jsonDef = jsonArray.getJSONObject(arrayIndex); defs.add(new BlockDefinition(jsonDef)); } } catch (JSONException e) { String msg = "Block definition #" + arrayIndex + ": " + e.getMessage(); throw new BlockLoadingException(msg, e); } // Attempt to add each definition, catching redefinition errors. int blockAddedCount = 0; for (arrayIndex = 0; arrayIndex < defs.size(); ++arrayIndex) { BlockDefinition def = defs.get(arrayIndex); String typeName = def.getTypeName(); // Replace prior definition with warning, mimicking web behavior. if (removeDefinition(typeName)) { Log.w(TAG, "Block definition #" + arrayIndex + " in JSON array replaces prior definition of \"" + typeName + "\"."); } addDefinition(def); blockAddedCount++; } return blockAddedCount; } /** * Registers a {@link Mutator.Factory} for the named mutator type. * @param mutatorId The name / id of this mutator type. * @param mutatorFactory The factory for this mutator type. */ public void registerMutator(String mutatorId, Mutator.Factory mutatorFactory) { Mutator.Factory old = mMutatorFactories.get(mutatorId); if (mutatorFactory == old) { return; } if (mutatorId != null && old != null) { if (mBlockRefs.isEmpty()) { Log.w(TAG, "Replacing reference to mutator \"" + mutatorId + "\"."); } else { // Make this explicit throw new IllegalStateException( "Mutator \"" + mutatorId + "\" already registered, and may be " + "referenced by a block. Must call removeMutator() first ."); } } mMutatorFactories.put(mutatorId, mutatorFactory); } /** * Registers a {@link BlockExtension} for Blocks. * @param extensionId The identifier used in BlockDefinition and JSON references. * @param extension The new extension. */ public void registerExtension(String extensionId, BlockExtension extension) { BlockExtension old = mExtensions.get(extensionId); if (extension == old) { return; } if (extension != null && old != null) { if (mBlockRefs.isEmpty()) { Log.w(TAG, "Replacing reference to BlockExtension \"" + extensionId + "\"."); } else { // Make this explicit throw new IllegalStateException( "BlockExtension \"" + extensionId + "\" already registered, and may be " + "referenced by a block. Must call removeExtension() first ."); } } mExtensions.put(extensionId, extension); } /** * Removes a block type definition from this factory. If any block of this type is still in use, * this may cause a crash if the user tries to load a new block of this type, including copies. * * @param definitionName The name of the block definition to remove. * @return True if the block definition was found and removed. Otherwise, false. */ public boolean removeDefinition(String definitionName) { boolean result = (mDefinitions.remove(definitionName) != null); if (result && !mBlockRefs.isEmpty()) { Log.w(TAG, "Removing BlockDefinition \"" + definitionName + "\" while blocks active."); } return result; } /** * Removes a {@link BlockExtension} from this block factory. If any block of this type is still * in use, this may cause a crash if the user tries to load a new block of this type, including * copies. * * @param extensionName The name of the extension to remove. * @return True if the extension was found and removed. Otherwise, false. */ public boolean removeExtension(String extensionName) { boolean result = (mExtensions.remove(extensionName) != null); if (result && !mBlockRefs.isEmpty()) { Log.w(TAG, "Removing BlockExtension \"" + extensionName + "\" while blocks active."); } return result; } /** * Creates a block of the specified type using a {@link BlockDefinition} registered with this * factory. If the {@code definitionName} is not one of the known block types null will be * returned instead. * * This version is used for testing. * {@code obtain(new BlockTemplate().ofType(definitionName).withId(id));} should be use instead. * * @param definitionName The name of the block type to create. * @param id The id of the block if loaded from XML; null otherwise. * @return A new block of that type or null. * @throws IllegalArgumentException If id is not null and already refers to a block. */ @VisibleForTesting Block obtainBlock(String definitionName, @Nullable String id) { // Validate id is available. if (id != null && isBlockIdInUse(id)) { throw new IllegalArgumentException("Block id \"" + id + "\" already in use."); } // Verify definition is defined. if (!mDefinitions.containsKey(definitionName)) { Log.w(TAG, "Block " + definitionName + " not found."); return null; } try { return obtainBlockFrom(new BlockTemplate().ofType(definitionName).withId(id)); } catch (BlockLoadingException e) { return null; } } /** * Creates the {@link Block} described by the template. * * <pre>{@code * blockFactory.obtainBlockFrom(new BlockTemplate().shadow().ofType("math_number")); * }</pre> * * @param template A template of the block to create. * @return A new block, or null if not able to construct it. */ public Block obtainBlockFrom(BlockTemplate template) throws BlockLoadingException { if (mController == null) { throw new IllegalStateException("Must set BlockController before creating block."); } String id = getCheckedId(template.mId); // Existing instance not found. Constructing a new Block. BlockDefinition definition; boolean isShadow = (template.mIsShadow == null) ? false : template.mIsShadow; Block block; if (template.mCopySource != null) { try { // TODO: Improve copy overhead. Template from copy to avoid XML I/O? String xml = BlocklyXmlHelper.writeBlockToXml(template.mCopySource, IOOptions.WRITE_ROOT_ONLY_WITHOUT_ID); String escapedId = BlocklyXmlHelper.escape(id); xml = xml.replace("<block", "<block id=\"" + escapedId + "\""); block = BlocklyXmlHelper.loadOneBlockFromXml(xml, this); } catch (BlocklySerializerException e) { throw new BlockLoadingException( "Failed to serialize original " + template.mCopySource, e); } } else { // Start a new block from a block definition. if (template.mDefinition != null) { if (template.mTypeName != null && !template.mTypeName.equals(template.mDefinition.getTypeName())) { throw new BlockLoadingException("Conflicting block definitions referenced."); } definition = template.mDefinition; } else if (template.mTypeName != null) { definition = mDefinitions.get(template.mTypeName.trim()); if (definition == null) { throw new BlockLoadingException("Block definition named \"" + template.mTypeName + "\" not found."); } } else { throw new BlockLoadingException(template.toString() + " missing block definition."); } block = new Block(mController, this, definition, id, isShadow); } // Apply mutable state last. template.applyMutableState(block); mBlockRefs.put(block.getId(), new WeakReference<>(block)); return block; } /** * @return The list of known blocks types. */ public List<BlockDefinition> getAllBlockDefinitions() { return new ArrayList<>(mDefinitions.values()); } /** * Create a new {@link Field} instance from JSON. If the type is not recognized * null will be returned. If the JSON is invalid or there is an error reading the data a * {@link RuntimeException} will be thrown. * * @param blockType The type id of the block within this field will be contained. * @param json The JSON to generate the Field from. * * @return A Field of the appropriate type. * * @throws RuntimeException */ public Field loadFieldFromJson(String blockType, JSONObject json) throws BlockLoadingException { String type = null; try { type = json.getString("type"); } catch (JSONException e) { throw new BlockLoadingException("Error getting the field type.", e); } // If new fields are added here FIELD_TYPES should also be updated. Field field = null; switch (type) { case Field.TYPE_LABEL_STRING: field = FieldLabel.fromJson(json); break; case Field.TYPE_INPUT_STRING: field = FieldInput.fromJson(json); break; case Field.TYPE_ANGLE_STRING: field = FieldAngle.fromJson(json); break; case Field.TYPE_CHECKBOX_STRING: field = FieldCheckbox.fromJson(json); break; case Field.TYPE_COLOR_STRING: field = FieldColor.fromJson(json); break; case Field.TYPE_DATE_STRING: field = FieldDate.fromJson(json); break; case Field.TYPE_VARIABLE_STRING: field = FieldVariable.fromJson(json); break; case Field.TYPE_DROPDOWN_STRING: field = FieldDropdown.fromJson(json); String fieldName = field.getName(); if (!TextUtils.isEmpty(blockType) && !TextUtils.isEmpty(fieldName)) { // While block type names should be unique, if there is a collision, the latest // block and its option type wins. mDropdownOptions.put( new BlockTypeFieldName(blockType, fieldName), new WeakReference<>(((FieldDropdown) field).getOptions())); } break; case Field.TYPE_IMAGE_STRING: field = FieldImage.fromJson(json); break; case Field.TYPE_NUMBER_STRING: field = FieldNumber.fromJson(json); break; default: Log.w(TAG, "Unknown field type."); break; } return field; } /** * Applies the named mutator to the provided block. */ public void applyMutator(String mutatorId, Block block) throws BlockLoadingException { Mutator.Factory factory = mMutatorFactories.get(mutatorId); if (factory == null) { throw new BlockLoadingException("Unknown mutator \"" + mutatorId + "\"."); } block.setMutator(factory.newMutator(mController)); } /** * Applies the named extension to the provided block. * @param extensionId The name / id of the extension, as seen in the JSON extensions attribute. * @param block The block to apply it to. */ public void applyExtension(String extensionId, Block block) throws BlockLoadingException { BlockExtension extension = mExtensions.get(extensionId); if (extension == null) { throw new BlockLoadingException("Unknown extension \"" + extensionId + "\"."); } Mutator old = block.getMutator(); extension.applyTo(block); if (block.getMutator() != old) { // Unlike web, Android mutators are not assigned by extensions. Log.w(TAG, "Extensions are not allowed to assign mutators. " + "Use Mutator and Mutator.Factory class."); } } /** * Load a block and all of its children from XML. * * @param parser An XmlPullParser pointed at the start tag of this block. * @return The loaded block. * @throws BlockLoadingException If unable to load the block or child. May contain a * XmlPullParserException or IOException as a root cause. */ public Block fromXml(XmlPullParser parser) throws BlockLoadingException { int startLine = parser.getLineNumber(); BlockLoadingException childException = null; final XmlBlockTemplate template = new XmlBlockTemplate(); try { String type = parser.getAttributeValue(null, "type"); // prototype name if (type == null || (type = type.trim()).isEmpty()) { throw new BlockLoadingException("Block is missing a type."); } template.ofType(type); template.withId(parser.getAttributeValue(null, "id")); // If the id was empty the BlockFactory will just generate one. String collapsedString = parser.getAttributeValue(null, "collapsed"); if (collapsedString != null) { template.collapsed(Boolean.parseBoolean(collapsedString)); } String deletableString = parser.getAttributeValue(null, "deletable"); if (deletableString != null) { template.deletable(Boolean.parseBoolean(deletableString)); } String disabledString = parser.getAttributeValue(null, "disabled"); if (disabledString != null) { template.disabled(Boolean.parseBoolean(disabledString)); } String editableString = parser.getAttributeValue(null, "editable"); if (editableString != null) { template.editable(Boolean.parseBoolean(editableString)); } String inputsInlineString = parser.getAttributeValue(null, "inline"); if (inputsInlineString != null) { template.withInlineInputs(Boolean.parseBoolean(inputsInlineString)); } String movableString = parser.getAttributeValue(null, "movable"); if (movableString != null) { template.movable(Boolean.parseBoolean(movableString)); } // Set position. Only if this is a top level block. String x = parser.getAttributeValue(null, "x"); String y = parser.getAttributeValue(null, "y"); if (x != null && y != null) { template.atPosition(Float.parseFloat(x), Float.parseFloat(y)); } int eventType = parser.next(); String text = ""; String fieldName = ""; Block childBlock = null; Block childShadow = null; String inputName = null; while (eventType != XmlPullParser.END_DOCUMENT) { String tagname = parser.getName(); switch (eventType) { case XmlPullParser.START_TAG: text = ""; // Ignore text from parent (or prior) block. if (tagname.equalsIgnoreCase("block")) { try { childBlock = fromXml(parser); } catch (BlockLoadingException e) { childException = e; // Save reference to pass through outer catch throw e; } } else if (tagname.equalsIgnoreCase("shadow")) { try { childShadow = fromXml(parser); } catch (BlockLoadingException e) { childException = e; // Save reference to pass through outer catch throw e; } } else if (tagname.equalsIgnoreCase("field")) { fieldName = parser.getAttributeValue(null, "name"); } else if (tagname.equalsIgnoreCase("value") || tagname.equalsIgnoreCase("statement")) { inputName = parser.getAttributeValue(null, "name"); if (TextUtils.isEmpty(inputName)) { throw new BlockLoadingException( "<" + tagname + "> must have a name attribute."); } } else if (tagname.equalsIgnoreCase("mutation")) { String elementStr = BlocklyXmlHelper.captureElement(parser); template.withMutation(elementStr); } break; case XmlPullParser.TEXT: text = parser.getText(); break; case XmlPullParser.END_TAG: if (tagname.equalsIgnoreCase("block")) { return obtainBlockFrom(template); } else if (tagname.equalsIgnoreCase("shadow")) { template.shadow(); return obtainBlockFrom(template); } else if (tagname.equalsIgnoreCase("field")) { if (TextUtils.isEmpty(fieldName)) { Log.w(TAG, "Ignoring unnamed field in " + template.toString("block")); } else { template.withFieldValue(fieldName, text); } fieldName = null; text = ""; } else if (tagname.equalsIgnoreCase("comment")) { template.withComment(text); text = ""; } else if (tagname.equalsIgnoreCase("value") || tagname.equalsIgnoreCase("statement")) { if (inputName == null) { // Start tag missing input name. Should catch this above. throw new BlockLoadingException("Missing inputName."); } try { template.withInputValue(inputName, childBlock, childShadow); } catch (IllegalArgumentException e) { throw new BlockLoadingException(template.toString("Block") + " input \"" + inputName + "\": " + e.getMessage()); } childBlock = null; childShadow = null; inputName = null; } else if (tagname.equalsIgnoreCase("next")) { template.withNextChild(childBlock, childShadow); childBlock = null; childShadow = null; } break; default: break; } eventType = parser.next(); } throw new BlockLoadingException("Reached the END_DOCUMENT before end of block."); } catch (BlockLoadingException | XmlPullParserException | IOException e) { if (e == childException) { throw (BlockLoadingException) e; // Pass through unchanged. } String msg = "Error"; int errorLine = parser.getLineNumber(); if (errorLine > -1) { int errorCol = parser.getColumnNumber(); msg += " at line " + errorLine + ", col " + errorCol; } msg += " loading " + template.toString("block"); if (startLine > -1) { msg += " starting at line " + startLine; } throw new BlockLoadingException(msg + ": " + e.getMessage(), e); } } /** * Updates the list of options used by dropdowns in select block types. These fields must be * derived from the prototype blocks loaded via JSON (via {@link #obtainBlock}), and where * {@link FieldDropdown#setOptions(FieldDropdown.Options)} has not been called. An instance of * the block must already exist, usually the prototype loaded via JSON. * * @param blockType The name for the type of block containing such fields * @param fieldName The name of the field within the block. * @param optionList The list of {@link FieldDropdown.Option}s used to to set for the * referenced dropdowns. */ public void updateDropdownOptions(String blockType, String fieldName, List<FieldDropdown.Option> optionList) { BlockTypeFieldName key = new BlockTypeFieldName(blockType, fieldName); WeakReference<FieldDropdown.Options> sharedOptionsRef = mDropdownOptions.get(key); FieldDropdown.Options sharedOptions = sharedOptionsRef == null ? null : sharedOptionsRef.get(); if (sharedOptions == null) { sharedOptions = new FieldDropdown.Options(optionList); mDropdownOptions.put(key, new WeakReference<>(sharedOptions)); } else { sharedOptions.updateOptions(optionList); } } /** * Removes all blocks from the factory. */ public void clear() { mBlockRefs.clear(); // What if these blocks exist on the workspace? mDefinitions.clear(); mExtensions.clear(); mDropdownOptions.clear(); } /** * Removes references to previous blocks. This can be used when resetting a workspace to force * a cleanup of known block instances. */ public void clearWorkspaceBlockReferences(String workspaceId) { List<String> idsToRemove = new ArrayList<>(mBlockRefs.size()); for (String blockId : mBlockRefs.keySet()) { WeakReference<Block> ref = mBlockRefs.get(blockId); Block block = ref.get(); if (block == null || workspaceId.equals(block.getEventWorkspaceId())) { idsToRemove.add(blockId); } } for (String id : idsToRemove) { mBlockRefs.remove(id); } } /** * Returns an id that is statistically unique. * @param requested The requested id. * @return The allowed id. * @throws BlockLoadingException If a collision occurs when the id is required. */ private String getCheckedId(String requested) throws BlockLoadingException { if (requested != null) { if (!isBlockIdInUse(requested)) { return requested; } } String id = UUID.randomUUID().toString(); while(mBlockRefs.containsKey(id)) { // Exceptionally unlikely, but... id = UUID.randomUUID().toString(); } return id; } public boolean isDefined(String definitionId) { return mDefinitions.containsKey(definitionId); } /** Child blocks for a named input. Used by {@link XmlBlockTemplate}. */ private static class InputValue { /** The name of the input */ final String mName; /** The child block. */ final Block mChild; /** The connected shadow block. */ final Block mShadow; InputValue(String name, Block child, Block shadow) { mName = name; mChild = child; mShadow = shadow; } } /** * Extension of BlockTemplate that includes child blocks. This class is private, because child * block references in templates are strictly limited to one use, and this class in not intended * for use outside XML deserialization. */ private class XmlBlockTemplate extends BlockTemplate { /** Ordered list of input names and blocks, as loaded during XML deserialization. */ protected List<InputValue> mInputValues; /** * Sets a block input's child block and shadow. Child blocks in templates are only good * once, as the second time the child already has a parent. Only used during XML * deserialization. * * @param inputName The name of the field. * @param child The deserialized child block. * @param shadow The deserialized shadow block. * @return This block descriptor, for chaining. * @throws BlockLoadingException If inputName is not a valid name; if child or shadow are * not configured as such; if child or shadow overwrites a * prior value. */ private XmlBlockTemplate withInputValue(String inputName, Block child, Block shadow) throws BlockLoadingException { if (inputName == null || (inputName = inputName.trim()).length() == 0) { // Trim and test name throw new BlockLoadingException("Invalid input value name."); } // Validate child block shadow state and upward connection. if (child != null && (child.isShadow() || child.getUpwardsConnection() == null)) { throw new BlockLoadingException("Invalid input value block."); } if (shadow != null && (!shadow.isShadow() || shadow.getUpwardsConnection() == null)) { throw new BlockLoadingException("Invalid input shadow block."); } if (mInputValues == null) { mInputValues = new ArrayList<>(); } else { // Check for prior assignments to the same input value. Iterator<InputValue> iter = mInputValues.iterator(); while (iter.hasNext()) { InputValue priorValue = iter.next(); if (priorValue.mName.equals(inputName)) { boolean overwriteChild = child != null && priorValue.mChild != null && child != priorValue.mChild; boolean overwriteShadow = shadow != null & priorValue.mShadow != null && shadow != priorValue.mShadow; if (overwriteChild || overwriteShadow) { throw new IllegalArgumentException( "Input \"" + inputName + "\" already assigned."); } child = (child == null ? priorValue.mChild : child); shadow = (shadow == null ? priorValue.mShadow : shadow); iter.remove(); // Replaced below } } } mInputValues.add(new InputValue(inputName, child, shadow)); return this; } /** * Sets a block's next children. Child blocks in templates are only good once, as the second * time the child already has a parent. Only used during XML deserialization. * * @param child The deserialized child block. * @param shadow The deserialized shadow block. * @return This block descriptor, for chaining. * @throws BlockLoadingException If inputName is not a valid name; if child or shadow are * not configured as such; if child or shadow overwrites a * prior value. */ private XmlBlockTemplate withNextChild(Block child, Block shadow) throws BlockLoadingException { if (child != null && (child.isShadow() || child.getPreviousConnection() == null)) { throw new BlockLoadingException("Invalid next child block."); } if (shadow != null && (!shadow.isShadow() || shadow.getPreviousConnection() == null)) { throw new BlockLoadingException("Invalid next child shadow."); } mNextChild = child; mNextShadow = shadow; return this; } /** Appends child blocks after the rest of the template state. */ @Override public void applyMutableState(Block block) throws BlockLoadingException { super.applyMutableState(block); // TODO: Use the controller for the following block connections, in order to fire // events. if (mInputValues != null) { for (InputValue inputValue : mInputValues) { Input input = block.getInputByName(inputValue.mName); if (input == null) { throw new BlockLoadingException( toString() + ": No input with name \"" + inputValue.mName + "\""); } Connection connection = input.getConnection(); if (connection == null) { throw new BlockLoadingException( "Input \"" + inputValue.mName + "\" does not have a connection."); } block.connectOrThrow( input.getType() == Input.TYPE_STATEMENT ? "statement" : "value", connection, inputValue.mChild, inputValue.mShadow); } } if (mNextChild != null || mNextShadow != null) { Connection connection = block.getNextConnection(); if (connection == null) { throw new BlockLoadingException( this + "does not have a connection for next child."); } block.connectOrThrow("next", connection, mNextChild, mNextShadow); } } } }
googleapis/google-cloud-java
36,321
java-speech/proto-google-cloud-speech-v1p1beta1/src/main/java/com/google/cloud/speech/v1p1beta1/ListPhraseSetResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/speech/v1p1beta1/cloud_speech_adaptation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.speech.v1p1beta1; /** * * * <pre> * Message returned to the client by the `ListPhraseSet` method. * </pre> * * Protobuf type {@code google.cloud.speech.v1p1beta1.ListPhraseSetResponse} */ public final class ListPhraseSetResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v1p1beta1.ListPhraseSetResponse) ListPhraseSetResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListPhraseSetResponse.newBuilder() to construct. private ListPhraseSetResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListPhraseSetResponse() { phraseSets_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListPhraseSetResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListPhraseSetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListPhraseSetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse.class, com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse.Builder.class); } public static final int PHRASE_SETS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.speech.v1p1beta1.PhraseSet> phraseSets_; /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.speech.v1p1beta1.PhraseSet> getPhraseSetsList() { return phraseSets_; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.speech.v1p1beta1.PhraseSetOrBuilder> getPhraseSetsOrBuilderList() { return phraseSets_; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ @java.lang.Override public int getPhraseSetsCount() { return phraseSets_.size(); } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ @java.lang.Override public com.google.cloud.speech.v1p1beta1.PhraseSet getPhraseSets(int index) { return phraseSets_.get(index); } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ @java.lang.Override public com.google.cloud.speech.v1p1beta1.PhraseSetOrBuilder getPhraseSetsOrBuilder(int index) { return phraseSets_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < phraseSets_.size(); i++) { output.writeMessage(1, phraseSets_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < phraseSets_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, phraseSets_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse)) { return super.equals(obj); } com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse other = (com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse) obj; if (!getPhraseSetsList().equals(other.getPhraseSetsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getPhraseSetsCount() > 0) { hash = (37 * hash) + PHRASE_SETS_FIELD_NUMBER; hash = (53 * hash) + getPhraseSetsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message returned to the client by the `ListPhraseSet` method. * </pre> * * Protobuf type {@code google.cloud.speech.v1p1beta1.ListPhraseSetResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v1p1beta1.ListPhraseSetResponse) com.google.cloud.speech.v1p1beta1.ListPhraseSetResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListPhraseSetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListPhraseSetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse.class, com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse.Builder.class); } // Construct using com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (phraseSetsBuilder_ == null) { phraseSets_ = java.util.Collections.emptyList(); } else { phraseSets_ = null; phraseSetsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.speech.v1p1beta1.SpeechAdaptationProto .internal_static_google_cloud_speech_v1p1beta1_ListPhraseSetResponse_descriptor; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse getDefaultInstanceForType() { return com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse build() { com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse buildPartial() { com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse result = new com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse result) { if (phraseSetsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { phraseSets_ = java.util.Collections.unmodifiableList(phraseSets_); bitField0_ = (bitField0_ & ~0x00000001); } result.phraseSets_ = phraseSets_; } else { result.phraseSets_ = phraseSetsBuilder_.build(); } } private void buildPartial0(com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse) { return mergeFrom((com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse other) { if (other == com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse.getDefaultInstance()) return this; if (phraseSetsBuilder_ == null) { if (!other.phraseSets_.isEmpty()) { if (phraseSets_.isEmpty()) { phraseSets_ = other.phraseSets_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePhraseSetsIsMutable(); phraseSets_.addAll(other.phraseSets_); } onChanged(); } } else { if (!other.phraseSets_.isEmpty()) { if (phraseSetsBuilder_.isEmpty()) { phraseSetsBuilder_.dispose(); phraseSetsBuilder_ = null; phraseSets_ = other.phraseSets_; bitField0_ = (bitField0_ & ~0x00000001); phraseSetsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPhraseSetsFieldBuilder() : null; } else { phraseSetsBuilder_.addAllMessages(other.phraseSets_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.speech.v1p1beta1.PhraseSet m = input.readMessage( com.google.cloud.speech.v1p1beta1.PhraseSet.parser(), extensionRegistry); if (phraseSetsBuilder_ == null) { ensurePhraseSetsIsMutable(); phraseSets_.add(m); } else { phraseSetsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.speech.v1p1beta1.PhraseSet> phraseSets_ = java.util.Collections.emptyList(); private void ensurePhraseSetsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { phraseSets_ = new java.util.ArrayList<com.google.cloud.speech.v1p1beta1.PhraseSet>(phraseSets_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v1p1beta1.PhraseSet, com.google.cloud.speech.v1p1beta1.PhraseSet.Builder, com.google.cloud.speech.v1p1beta1.PhraseSetOrBuilder> phraseSetsBuilder_; /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public java.util.List<com.google.cloud.speech.v1p1beta1.PhraseSet> getPhraseSetsList() { if (phraseSetsBuilder_ == null) { return java.util.Collections.unmodifiableList(phraseSets_); } else { return phraseSetsBuilder_.getMessageList(); } } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public int getPhraseSetsCount() { if (phraseSetsBuilder_ == null) { return phraseSets_.size(); } else { return phraseSetsBuilder_.getCount(); } } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public com.google.cloud.speech.v1p1beta1.PhraseSet getPhraseSets(int index) { if (phraseSetsBuilder_ == null) { return phraseSets_.get(index); } else { return phraseSetsBuilder_.getMessage(index); } } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder setPhraseSets(int index, com.google.cloud.speech.v1p1beta1.PhraseSet value) { if (phraseSetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePhraseSetsIsMutable(); phraseSets_.set(index, value); onChanged(); } else { phraseSetsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder setPhraseSets( int index, com.google.cloud.speech.v1p1beta1.PhraseSet.Builder builderForValue) { if (phraseSetsBuilder_ == null) { ensurePhraseSetsIsMutable(); phraseSets_.set(index, builderForValue.build()); onChanged(); } else { phraseSetsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder addPhraseSets(com.google.cloud.speech.v1p1beta1.PhraseSet value) { if (phraseSetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePhraseSetsIsMutable(); phraseSets_.add(value); onChanged(); } else { phraseSetsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder addPhraseSets(int index, com.google.cloud.speech.v1p1beta1.PhraseSet value) { if (phraseSetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePhraseSetsIsMutable(); phraseSets_.add(index, value); onChanged(); } else { phraseSetsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder addPhraseSets( com.google.cloud.speech.v1p1beta1.PhraseSet.Builder builderForValue) { if (phraseSetsBuilder_ == null) { ensurePhraseSetsIsMutable(); phraseSets_.add(builderForValue.build()); onChanged(); } else { phraseSetsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder addPhraseSets( int index, com.google.cloud.speech.v1p1beta1.PhraseSet.Builder builderForValue) { if (phraseSetsBuilder_ == null) { ensurePhraseSetsIsMutable(); phraseSets_.add(index, builderForValue.build()); onChanged(); } else { phraseSetsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder addAllPhraseSets( java.lang.Iterable<? extends com.google.cloud.speech.v1p1beta1.PhraseSet> values) { if (phraseSetsBuilder_ == null) { ensurePhraseSetsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, phraseSets_); onChanged(); } else { phraseSetsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder clearPhraseSets() { if (phraseSetsBuilder_ == null) { phraseSets_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { phraseSetsBuilder_.clear(); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public Builder removePhraseSets(int index) { if (phraseSetsBuilder_ == null) { ensurePhraseSetsIsMutable(); phraseSets_.remove(index); onChanged(); } else { phraseSetsBuilder_.remove(index); } return this; } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public com.google.cloud.speech.v1p1beta1.PhraseSet.Builder getPhraseSetsBuilder(int index) { return getPhraseSetsFieldBuilder().getBuilder(index); } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public com.google.cloud.speech.v1p1beta1.PhraseSetOrBuilder getPhraseSetsOrBuilder(int index) { if (phraseSetsBuilder_ == null) { return phraseSets_.get(index); } else { return phraseSetsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public java.util.List<? extends com.google.cloud.speech.v1p1beta1.PhraseSetOrBuilder> getPhraseSetsOrBuilderList() { if (phraseSetsBuilder_ != null) { return phraseSetsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(phraseSets_); } } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public com.google.cloud.speech.v1p1beta1.PhraseSet.Builder addPhraseSetsBuilder() { return getPhraseSetsFieldBuilder() .addBuilder(com.google.cloud.speech.v1p1beta1.PhraseSet.getDefaultInstance()); } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public com.google.cloud.speech.v1p1beta1.PhraseSet.Builder addPhraseSetsBuilder(int index) { return getPhraseSetsFieldBuilder() .addBuilder(index, com.google.cloud.speech.v1p1beta1.PhraseSet.getDefaultInstance()); } /** * * * <pre> * The phrase set. * </pre> * * <code>repeated .google.cloud.speech.v1p1beta1.PhraseSet phrase_sets = 1;</code> */ public java.util.List<com.google.cloud.speech.v1p1beta1.PhraseSet.Builder> getPhraseSetsBuilderList() { return getPhraseSetsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v1p1beta1.PhraseSet, com.google.cloud.speech.v1p1beta1.PhraseSet.Builder, com.google.cloud.speech.v1p1beta1.PhraseSetOrBuilder> getPhraseSetsFieldBuilder() { if (phraseSetsBuilder_ == null) { phraseSetsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v1p1beta1.PhraseSet, com.google.cloud.speech.v1p1beta1.PhraseSet.Builder, com.google.cloud.speech.v1p1beta1.PhraseSetOrBuilder>( phraseSets_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); phraseSets_ = null; } return phraseSetsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.speech.v1p1beta1.ListPhraseSetResponse) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v1p1beta1.ListPhraseSetResponse) private static final com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse(); } public static com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListPhraseSetResponse> PARSER = new com.google.protobuf.AbstractParser<ListPhraseSetResponse>() { @java.lang.Override public ListPhraseSetResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListPhraseSetResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListPhraseSetResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/coherence
36,166
prj/test/functional/cache/src/main/java/cache/BaseAsyncNamedCacheTests.java
/* * Copyright (c) 2000, 2023, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package cache; import com.oracle.bedrock.testsupport.deferred.Eventually; import com.oracle.coherence.testing.util.JacocoHelper; import com.tangosol.net.AsyncNamedCache; import com.tangosol.net.AsyncNamedMap; import com.tangosol.net.NamedCache; import com.tangosol.util.Filter; import com.tangosol.util.Filters; import com.tangosol.util.InvocableMap; import com.tangosol.util.InvocableMap.EntryAggregator; import com.tangosol.util.NullImplementation; import com.tangosol.util.SimpleHolder; import com.tangosol.util.ValueExtractor; import com.tangosol.util.aggregator.CompositeAggregator; import com.tangosol.util.aggregator.Count; import com.tangosol.util.aggregator.LongSum; import com.tangosol.util.extractor.IdentityExtractor; import com.tangosol.util.filter.AlwaysFilter; import com.tangosol.util.filter.GreaterFilter; import com.tangosol.util.filter.NeverFilter; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Unit tests for AsyncNamedCache. * * @author as 2015.01.21 */ @SuppressWarnings({"CallToPrintStackTrace", "DuplicatedCode"}) public abstract class BaseAsyncNamedCacheTests { /** * Create a {@link BaseAsyncNamedCacheTests} instance. * * @param sCacheName the cache name to test (should map to a valid name in the coherence-cache-config.xml file * in this module's resources/ folder). * @param options the {@link AsyncNamedMap.Option options} to use to create the async maps to test */ protected BaseAsyncNamedCacheTests(String sCacheName, AsyncNamedMap.Option... options) { f_sCacheName = sCacheName; f_options = options; } /** * Return the cache used by the tests. * <p/> * This should be the plain {@link NamedCache} not an * {@link com.tangosol.net.AsyncNamedCache}. * * @param <K> the cache key type * @param <V> the cache value type * * @return the cache used by the tests */ protected <K, V> NamedCache<K, V> getNamedCache() { return getNamedCache(f_sCacheName); } /** * Return the cache used by the tests. * <p/> * This should be the plain {@link NamedCache} not an * {@link com.tangosol.net.AsyncNamedCache}. * * @param <K> the cache key type * @param <V> the cache value type * * @return the cache used by the tests */ protected abstract <K, V> NamedCache<K, V> getNamedCache(String sCacheName); @Test public void shouldCallInvoke() throws Exception { NamedCache<Integer, Integer> cache = getNamedCache(); cache.put(2, 2); SimpleHolder<Integer> holder = new SimpleHolder<>(); assertEquals(2, (int) cache.async(f_options).invoke(2, multiplier(2)) .whenComplete((r, t) -> System.out.println("testInvoke: " + r)) .whenComplete((r, t) -> holder.set(r)) .get(1, TimeUnit.MINUTES)); assertEquals(4, (int) cache.get(2)); assertEquals(2, (int) holder.get()); } @Test(expected = ExecutionException.class) public void shouldCallInvokeWithException() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(2, "two"); cache.async(f_options).invoke(2, BaseAsyncNamedCacheTests::error) .whenComplete((r, t) -> t.printStackTrace()).get(1, TimeUnit.MINUTES); } @Test public void shouldCallInvokeAllWithKeySet() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); Map<String, Integer> expected = new HashMap<>(); expected.put("1", 1); expected.put("3", 9); assertEquals(expected, cache.async(f_options) .invokeAll(Arrays.asList("1", "3"), BaseAsyncNamedCacheTests::square) .whenComplete((r, t) -> System.out.println("testInvokeAllWithKeySet: " + r)) .get(1, TimeUnit.MINUTES)); } @Test public void shouldCallInvokeAllWithFilter() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); Map<String, Integer> expected = new HashMap<>(); expected.put("2", 4); expected.put("3", 9); assertEquals(expected, cache.async(f_options).invokeAll(GREATER_THAN_1, BaseAsyncNamedCacheTests::square) .whenComplete((r, t) -> System.out.println("testInvokeAllWithFilter: " + r)).get(1, TimeUnit.MINUTES)); expected = cache.async(f_options).invokeAll(NeverFilter.INSTANCE(), BaseAsyncNamedCacheTests::square) .whenComplete((r, t) -> System.out.println("testInvokeAllWithFilter: " + r)).get(1, TimeUnit.MINUTES); assertEquals(0, expected.size()); Set<?> expected2 = cache.async(f_options).entrySet(NeverFilter.INSTANCE()) .whenComplete((r, t) -> System.out.println("testInvokeAllWithFilter: " + r)).get(1, TimeUnit.MINUTES); assertEquals(0, expected2.size()); } // ---- query methods --------------------------------------------------- @Test public void shouldCallKeySet() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); assertEquals(cache.keySet(), cache.async(f_options).keySet().get(1, TimeUnit.MINUTES)); } @Test public void shouldCallKeySetWithFilter() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Filter<?> filter = Filters.like(ValueExtractor.identity(), "A%"); assertEquals(cache.keySet(filter), cache.async(f_options).keySet(filter).get(1, TimeUnit.MINUTES)); filter = Filters.like(ValueExtractor.identity(), "Z%"); assertEquals(0, cache.async(f_options).keySet(filter).get(1, TimeUnit.MINUTES).size()); } @Test public void shouldStreamKeySet() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Set<Integer> setResults = new HashSet<>(); cache.async(f_options).keySet(setResults::add).get(1, TimeUnit.MINUTES); assertEquals(2, setResults.size()); assertTrue(setResults.contains(1)); assertTrue(setResults.contains(2)); setResults.clear(); Filter<?> filter = Filters.like(ValueExtractor.identity(), "A%"); cache.async(f_options).keySet(filter, setResults::add).get(1, TimeUnit.MINUTES); assertEquals(1, setResults.size()); assertTrue(setResults.contains(1)); } @Test(expected = ExecutionException.class) public void shouldCallKeySetWithException() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Filter<?> filter = oTarget -> { throw new RuntimeException(); }; cache.async(f_options).keySet(filter).get(1, TimeUnit.MINUTES); } @Test public void shouldCallEntrySet() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); assertEquals(cache.entrySet(), cache.async(f_options).entrySet().get(1, TimeUnit.MINUTES)); } @Test public void shouldCallEntrySetWithFilter() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Filter<?> filter = Filters.like(ValueExtractor.identity(), "A%"); assertThat(cache.async(f_options).entrySet(filter).get(1, TimeUnit.MINUTES), is(cache.entrySet(filter))); filter = Filters.like(ValueExtractor.identity(), "Z%"); assertEquals(0, cache.async(f_options).entrySet(filter).get(1, TimeUnit.MINUTES).size()); } @Test public void shouldCallEntrySetWithComparator() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); assertEquals(cache.entrySet(AlwaysFilter.INSTANCE, null), cache.async(f_options).entrySet(AlwaysFilter.INSTANCE, (Comparator<?>) null).get(1, TimeUnit.MINUTES)); } @Test public void shouldStreamEntrySet() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Set<String> setResults = new HashSet<>(); cache.async(f_options).entrySet((key, value) -> setResults.add(value)).get(1, TimeUnit.MINUTES); assertEquals(2, setResults.size()); assertTrue(setResults.contains("Aleks")); assertTrue(setResults.contains("Marija")); setResults.clear(); Filter<?> filter = Filters.like(ValueExtractor.identity(), "A%"); cache.async(f_options).entrySet(filter, entry -> setResults.add(entry.getValue())).get(1, TimeUnit.MINUTES); assertEquals(1, setResults.size()); assertTrue(setResults.contains("Aleks")); } @Test(expected = ExecutionException.class) public void shouldCallEntrySetWithException() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Filter<?> filter = oTarget -> { throw new RuntimeException(); }; cache.async(f_options).entrySet(filter).get(1, TimeUnit.MINUTES); } @Test public void shouldCallValues() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); assertEquals(cache.values().size(), cache.async(f_options).values().get(1, TimeUnit.MINUTES).size()); assertTrue(cache.values().containsAll(cache.async(f_options).values().get(1, TimeUnit.MINUTES))); } @Test public void shouldCallValuesWithFilter() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Filter<?> filter = Filters.like(ValueExtractor.identity(), "A%"); assertEquals(new ArrayList<>(cache.values(filter, null)), new ArrayList<>(cache.async(f_options).values(filter, (Comparator<String>) null).get(1, TimeUnit.MINUTES))); filter = Filters.like(ValueExtractor.identity(), "Z%"); assertEquals(0, cache.async(f_options).values(filter).get(1, TimeUnit.MINUTES).size()); } @Test public void shouldStreamValues() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Set<String> setResults = new HashSet<>(); cache.async(f_options).values(setResults::add).get(1, TimeUnit.MINUTES); assertEquals(2, setResults.size()); assertTrue(setResults.contains("Aleks")); assertTrue(setResults.contains("Marija")); setResults.clear(); Filter<?> filter = Filters.like(ValueExtractor.identity(), "A%"); cache.async(f_options).values(filter, setResults::add).get(1, TimeUnit.MINUTES); assertEquals(1, setResults.size()); assertTrue(setResults.contains("Aleks")); } @Test(expected = ExecutionException.class) public void shouldCallValuesWithException() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.put(1, "Aleks"); cache.put(2, "Marija"); Filter<?> filter = oTarget -> { throw new RuntimeException(); }; cache.async(f_options).values(filter).get(1, TimeUnit.MINUTES); } // ---- Map methods ----------------------------------------------------- @Test public void shouldCallClear() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); AsyncNamedCache<Integer, String> async = cache.async(f_options); assertThat(async.size().get(1, TimeUnit.MINUTES), is(0)); assertThat(async.isEmpty().get(1, TimeUnit.MINUTES), is(true)); cache.put(1, "one"); cache.put(2, "two"); assertThat(async.size().get(1, TimeUnit.MINUTES), is(2)); assertThat(async.isEmpty().get(1, TimeUnit.MINUTES), is(false)); async.clear().get(1, TimeUnit.MINUTES); assertThat(cache.size(), is(0)); assertThat(async.size().get(1, TimeUnit.MINUTES), is(0)); assertThat(async.isEmpty().get(1, TimeUnit.MINUTES), is(true)); } @Test public void shouldCallContainsKey() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); AsyncNamedCache<Integer, String> async = cache.async(f_options); assertThat(async.containsKey(1).get(1, TimeUnit.MINUTES), is(false)); cache.put(1, "one"); assertThat(async.containsKey(1).get(1, TimeUnit.MINUTES), is(true)); cache.remove(1); assertThat(async.containsKey(1).get(1, TimeUnit.MINUTES), is(false)); } @Test public void shouldCallGetOrDefaultWhenKeyMappedToValue() throws Exception { JacocoHelper.skipIfJacocoInstrumented(); NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); assertThat(cache.async(f_options).getOrDefault("1", 100).get(1, TimeUnit.MINUTES), is(1)); } @Test public void shouldCallGetOrDefaultWhenKeyMappedToNull() throws Exception { JacocoHelper.skipIfJacocoInstrumented(); NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", null); assertThat(cache.async(f_options).getOrDefault("1", 100).get(1, TimeUnit.MINUTES), is(nullValue())); } @Test public void shouldCallGetOrDefaultWhenKeyNotPresent() throws Exception { JacocoHelper.skipIfJacocoInstrumented(); NamedCache<String, Integer> cache = getNamedCache(); cache.remove("1"); assertThat(cache.async(f_options).getOrDefault("1", 100).get(1, TimeUnit.MINUTES), is(100)); } @Test public void shouldCallGetOrDefault() throws Exception { JacocoHelper.skipIfJacocoInstrumented(); NamedCache<Integer, String> cache = getNamedCache(); cache.put(2, "two"); assertEquals("one", cache.async(f_options).getOrDefault(1, "one") .whenComplete((r, t) -> System.out.println("testGetOrDefault: " + r)) .get(1, TimeUnit.MINUTES)); assertEquals("two", cache.async(f_options).getOrDefault(2, "TWO") .whenComplete((r, t) -> System.out.println("testGetOrDefault: " + r)) .get(1, TimeUnit.MINUTES)); } @Test public void shouldCallGetAllWhereAllKeysMatch() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(2, 4, 6, 8); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(cache.async(f_options).getAll(listKeys).get(1, TimeUnit.MINUTES)); assertThat(mapCache.size(), is(listKeys.size())); assertThat(mapAsync.size(), is(listKeys.size())); assertThat(mapCache, hasEntry(2, "value-2")); assertThat(mapCache, hasEntry(4, "value-4")); assertThat(mapCache, hasEntry(6, "value-6")); assertThat(mapCache, hasEntry(8, "value-8")); assertThat(mapAsync, is(mapCache)); } @Test public void shouldCallGetAllWhereNoKeysMatch() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(22, 44, 66, 88); Map<Integer, String> mapCache = cache.getAll(listKeys); Map<Integer, String> mapAsync = cache.async(f_options).getAll(listKeys).get(1, TimeUnit.MINUTES); assertThat(mapCache.isEmpty(), is(true)); assertThat(mapAsync.isEmpty(), is(true)); } @Test public void shouldCallGetAllWhereSomeKeysMatch() throws Exception { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(22, 4, 66, 8); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(cache.async(f_options).getAll(listKeys).get(1, TimeUnit.MINUTES)); assertThat(mapCache.size(), is(2)); assertThat(mapAsync.size(), is(2)); assertThat(mapCache, hasEntry(4, "value-4")); assertThat(mapCache, hasEntry(8, "value-8")); assertThat(mapAsync, is(mapCache)); } @Test public void shouldCallGetAllWithConsumerWhereAllKeysMatch() { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(2, 4, 6, 8); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(); CompletableFuture<Void> future = cache.async(f_options) .getAll(listKeys, entry -> mapAsync.put(entry.getKey(), entry.getValue())); future.join(); assertThat(mapCache.size(), is(listKeys.size())); assertThat(mapAsync.size(), is(listKeys.size())); assertThat(mapCache, hasEntry(2, "value-2")); assertThat(mapCache, hasEntry(4, "value-4")); assertThat(mapCache, hasEntry(6, "value-6")); assertThat(mapCache, hasEntry(8, "value-8")); assertThat(mapAsync, is(mapCache)); } @Test public void shouldCallGetAlWithConsumerWhereNoKeysMatch() { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(22, 44, 66, 88); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(); CompletableFuture<Void> future = cache.async(f_options) .getAll(listKeys, entry -> mapAsync.put(entry.getKey(), entry.getValue())); future.join(); assertThat(mapCache.isEmpty(), is(true)); assertThat(mapAsync.isEmpty(), is(true)); } @Test public void shouldCallGetAllWithConsumerWhereSomeKeysMatch() { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(22, 4, 66, 8); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(); CompletableFuture<Void> future = cache.async(f_options) .getAll(listKeys, entry -> mapAsync.put(entry.getKey(), entry.getValue())); future.join(); assertThat(mapCache.size(), is(2)); assertThat(mapAsync.size(), is(2)); assertThat(mapCache, hasEntry(4, "value-4")); assertThat(mapCache, hasEntry(8, "value-8")); assertThat(mapAsync, is(mapCache)); } @Test public void shouldCallGetAllWithBiConsumerWhereAllKeysMatch() { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(2, 4, 6, 8); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(); CompletableFuture<Void> future = cache.async(f_options) .getAll(listKeys, mapAsync::put); future.join(); assertThat(mapCache.size(), is(listKeys.size())); assertThat(mapAsync.size(), is(listKeys.size())); assertThat(mapCache, hasEntry(2, "value-2")); assertThat(mapCache, hasEntry(4, "value-4")); assertThat(mapCache, hasEntry(6, "value-6")); assertThat(mapCache, hasEntry(8, "value-8")); assertThat(mapAsync, is(mapCache)); } @Test public void shouldCallGetAlWithBiConsumerWhereNoKeysMatch() { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(22, 44, 66, 88); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(); CompletableFuture<Void> future = cache.async(f_options) .getAll(listKeys, mapAsync::put); future.join(); assertThat(mapCache.isEmpty(), is(true)); assertThat(mapAsync.isEmpty(), is(true)); } @Test public void shouldCallGetAllWithBiConsumerWhereSomeKeysMatch() { NamedCache<Integer, String> cache = getNamedCache(); cache.clear(); for (int i = 0; i < 10; i++) { cache.put(i, "value-" + i); } List<Integer> listKeys = Arrays.asList(22, 4, 66, 8); Map<Integer, String> mapCache = new HashMap<>(cache.getAll(listKeys)); Map<Integer, String> mapAsync = new HashMap<>(); CompletableFuture<Void> future = cache.async(f_options) .getAll(listKeys, mapAsync::put); future.join(); assertThat(mapCache.size(), is(2)); assertThat(mapAsync.size(), is(2)); assertThat(mapCache, hasEntry(4, "value-4")); assertThat(mapCache, hasEntry(8, "value-8")); assertThat(mapAsync, is(mapCache)); } @Test public void shouldCallPut() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); AsyncNamedCache<String, Integer> async = cache.async(f_options); async.put("1", 1).get(1, TimeUnit.MINUTES); assertThat(cache.get("1"), is(1)); } @Test public void shouldCallPutWithExpiry() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); AsyncNamedCache<String, Integer> async = cache.async(f_options); async.put("1", 1, 5000L).get(1, TimeUnit.MINUTES); assertThat(cache.get("1"), is(1)); Eventually.assertDeferred(() -> cache.get("1"), is(nullValue())); } @Test public void shouldCallPutAll() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); AsyncNamedCache<String, Integer> async = cache.async(f_options); Map<String, Integer> map = Map.of("11", 11, "22", 22); async.putAll(map).get(1, TimeUnit.MINUTES); assertThat(cache.get("11"), is(11)); assertThat(cache.get("22"), is(22)); } @Test public void shouldCallPutAllWithExpiry() throws Exception { /* NOTE: If this test fails with UnsupportedOperationException when running in IntelliJ make sure the tangosol-coherence.xml file has not had the version in the license section overwritten by the IDE. If you see logs without a real version like this: "Oracle Coherence GE ${project.version.official} ${project.impl.description} " then you need to rebuild coherence. */ NamedCache<String, Integer> cache = getNamedCache(); AsyncNamedCache<String, Integer> async = cache.async(f_options); Map<String, Integer> map = Map.of("11", 11, "22", 22); async.putAll(map, 5000L).get(1, TimeUnit.MINUTES); assertThat(cache.get("11"), is(11)); assertThat(cache.get("22"), is(22)); Eventually.assertDeferred(cache::isEmpty, is(true)); } @Test public void shouldCallPutIfAbsent() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); AsyncNamedCache<String, Integer> async = cache.async(f_options); assertThat(async.putIfAbsent("1", 1).get(1, TimeUnit.MINUTES), is(nullValue())); assertThat(async.putIfAbsent("1", 100).get(1, TimeUnit.MINUTES), is(1)); assertThat(cache.get("1"), is(1)); cache.put("2", null); assertThat(cache.size(), is(2)); assertThat(async.putIfAbsent("2", 2).get(1, TimeUnit.MINUTES), is(nullValue())); assertThat(async.putIfAbsent("2", 200).get(1, TimeUnit.MINUTES), is(2)); assertThat(cache.get("2"), is(2)); } @Test public void shouldCallRemove() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); assertFalse(cache.async(f_options).remove("1", 2).get(1, TimeUnit.MINUTES)); assertTrue(cache.async(f_options).remove("2", 2).get(1, TimeUnit.MINUTES)); assertEquals(1, cache.size()); assertTrue(cache.containsKey("1")); assertFalse(cache.containsKey("2")); } @Test public void shouldCallReplace() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", null); assertEquals(1, (int) cache.async(f_options).replace("1", 100).get(1, TimeUnit.MINUTES)); assertNull(cache.async(f_options).replace("2", 200).get(1, TimeUnit.MINUTES)); assertNull(cache.async(f_options).replace("3", 300).get(1, TimeUnit.MINUTES)); assertEquals(2, cache.size()); assertFalse(cache.containsKey("3")); } @Test public void shouldCallReplaceWithValueCheck() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", null); cache.put("3", null); assertTrue(cache.async(f_options).replace("1", 1, 100).get(1, TimeUnit.MINUTES)); assertFalse(cache.async(f_options).replace("2", 2, 200).get(1, TimeUnit.MINUTES)); assertTrue(cache.async(f_options).replace("3", null, 300).get(1, TimeUnit.MINUTES)); assertFalse(cache.async(f_options).replace("4", 4, 400).get(1, TimeUnit.MINUTES)); assertEquals(100, (int) cache.get("1")); assertNull(cache.get("2")); assertEquals(300, (int) cache.get("3")); assertFalse(cache.containsKey("4")); } @Test public void shouldCallComputeIfAbsent() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("five", 5); assertEquals(1, (int) cache.async(f_options).computeIfAbsent("1", Integer::parseInt).get(1, TimeUnit.MINUTES)); assertEquals(5, (int) cache.async(f_options).computeIfAbsent("five", Integer::parseInt).get(1, TimeUnit.MINUTES)); assertNull(cache.async(f_options).computeIfAbsent("null", (k) -> null).get(1, TimeUnit.MINUTES)); } @Test public void shouldCallComputeIfPresent() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); assertEquals(2, (int) cache.async(f_options).computeIfPresent("1", (k, v) -> v + v).get(1, TimeUnit.MINUTES)); assertEquals(4, (int) cache.async(f_options).computeIfPresent("2", (k, v) -> v * v).get(1, TimeUnit.MINUTES)); assertNull(cache.async(f_options).computeIfPresent("1", (k, v) -> null).get(1, TimeUnit.MINUTES)); assertNull(cache.async(f_options).computeIfPresent("3", (k, v) -> v * v).get(1, TimeUnit.MINUTES)); assertEquals(4, (int) cache.get("2")); assertEquals(1, cache.size()); assertFalse(cache.containsKey("1")); } @Test public void shouldCallCompute() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); assertEquals(2, (int) cache.async(f_options).compute("1", (k, v) -> v + v).get(1, TimeUnit.MINUTES)); assertNull(cache.async(f_options).compute("2", (k, v) -> null).get(1, TimeUnit.MINUTES)); assertFalse(cache.containsKey("2")); } @Test public void shouldCallMerge() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); assertEquals(2, (int) cache.async(f_options).merge("1", 1, Integer::sum).get(1, TimeUnit.MINUTES)); assertEquals(3, (int) cache.async(f_options).merge("2", 1, Integer::sum).get(1, TimeUnit.MINUTES)); assertEquals(1, (int) cache.async(f_options).merge("3", 1, Integer::sum).get(1, TimeUnit.MINUTES)); assertNull(cache.async(f_options).merge("1", 1, (v1, v2) -> null).get(1, TimeUnit.MINUTES)); assertFalse(cache.containsKey("1")); assertTrue(cache.containsKey("3")); } @Test public void shouldCallReplaceAll() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); cache.async(f_options).replaceAll((k, v) -> v * v).get(1, TimeUnit.MINUTES); assertEquals(1, (int) cache.get("1")); assertEquals(4, (int) cache.get("2")); assertEquals(9, (int) cache.get("3")); } @Test public void shouldCallReplaceAllWithKeySet() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); cache.async(f_options).replaceAll(Arrays.asList("1", "3"), (k, v) -> v * v).get(1, TimeUnit.MINUTES); assertEquals(1, (int) cache.get("1")); assertEquals(2, (int) cache.get("2")); assertEquals(9, (int) cache.get("3")); } @Test public void shouldCallReplaceAllWithFilter() throws Exception { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); cache.async(f_options).replaceAll(GREATER_THAN_2, (k, v) -> v * v).get(1, TimeUnit.MINUTES); assertEquals(1, (int) cache.get("1")); assertEquals(2, (int) cache.get("2")); assertEquals(9, (int) cache.get("3")); } @Test public void shouldCallAggregate() { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); Count<String, Integer> count = new Count<>(); cache.async(f_options).aggregate(NullImplementation.getSet(), count) .thenAccept(x -> assertThat(x, is(0L))); cache.async(f_options).aggregate(cache.keySet(), new LongSum<>(IdentityExtractor.INSTANCE())) .thenAccept(x -> assertThat(x, is(6L))); } @Test public void shouldCallAggregateWithFilter() { NamedCache<String, Integer> cache = getNamedCache(); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); Count<String, Integer> count = new Count<>(); cache.async(f_options).aggregate((Filter<?>) null, count) .thenAccept(x -> assertThat(x, is(0))); cache.async(f_options).aggregate(AlwaysFilter.INSTANCE, count) .thenAccept(x -> assertThat(x, is(3))); cache.async(f_options).aggregate(AlwaysFilter.INSTANCE(), new LongSum<>(IdentityExtractor.INSTANCE())) .thenAccept(x -> assertThat(x, is(6L))); cache.async(f_options).aggregate( Filters.greater(x -> ((Integer) x), 1), new LongSum<>(IdentityExtractor.INSTANCE())) .thenAccept(x -> assertThat(x, is(5L))); } /** * Test of the {@link CompositeAggregator} aggregator. */ @Test @SuppressWarnings("unchecked") public void shouldCallCompositeAggregator() { NamedCache<Integer, Integer> cache = getNamedCache(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 1; i <= 10; ++i) { map.put(i, i); } cache.putAll(map); Set<Integer> setKeys = cache.keySet(); EntryAggregator<Integer, Integer, List<Number>> composite = CompositeAggregator.createInstance(new EntryAggregator[]{new Count<>(), new LongSum<>(IdentityExtractor.INSTANCE())}); cache.async(f_options).aggregate(setKeys, composite).thenAccept(x -> { assertEquals(x.get(0), 10); assertEquals(x.get(1), 55L); }); } // ---- helpers --------------------------------------------------------- public static Integer square(InvocableMap.Entry<?, Integer> entry) { return entry.getValue() * entry.getValue(); } public static NamedCache.EntryProcessor<Integer, Integer, Integer> multiplier(int n) { return (e) -> e.setValue(e.getValue() * n); } @SuppressWarnings({"NumericOverflow", "divzero"}) public static String error(InvocableMap.Entry<Integer, String> e) { return e.setValue(Integer.toString(5 / 0)); } protected static final GreaterFilter<?, ?> GREATER_THAN_1 = new GreaterFilter<>(IdentityExtractor.INSTANCE(), 1); protected static final GreaterFilter<?, ?> GREATER_THAN_2 = new GreaterFilter<>(IdentityExtractor.INSTANCE(), 2); // ----- data members --------------------------------------------------- /** * The cache name to test (should map to a valid name in the coherence-cache-config.xml file * in this module's resources/ folder). */ protected final String f_sCacheName; protected AsyncNamedMap.Option[] f_options; }
apache/harmony
36,401
classlib/modules/awt/src/main/java/common/java/awt/TextComponent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.awt; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.TextEvent; import java.awt.event.TextListener; import java.text.BreakIterator; import java.util.EventListener; import java.util.HashMap; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; import javax.accessibility.AccessibleText; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.PlainDocument; import javax.swing.text.View; import javax.swing.text.ViewFactory; import javax.swing.text.Position.Bias; import org.apache.harmony.awt.internal.nls.Messages; import org.apache.harmony.awt.state.TextComponentState; import org.apache.harmony.awt.text.AWTTextAction; import org.apache.harmony.awt.text.ActionNames; import org.apache.harmony.awt.text.ActionSet; import org.apache.harmony.awt.text.RootViewContext; import org.apache.harmony.awt.text.TextCaret; import org.apache.harmony.awt.text.TextFactory; import org.apache.harmony.awt.text.TextKit; public class TextComponent extends Component implements Accessible { private static final long serialVersionUID = -2214773872412987419L; /** * Maps KeyEvents to keyboard actions */ static class KeyMap { private static final HashMap<AWTKeyStroke, Object> actions = new HashMap<AWTKeyStroke, Object>(); static { add(KeyEvent.VK_ENTER, 0, ActionNames.insertBreakAction); add(KeyEvent.VK_TAB, 0, ActionNames.insertTabAction); add(KeyEvent.VK_DELETE, 0, ActionNames.deleteNextCharAction); add(KeyEvent.VK_BACK_SPACE, 0, ActionNames.deletePrevCharAction); add(KeyEvent.VK_LEFT, 0, ActionNames.backwardAction); add(KeyEvent.VK_RIGHT, 0, ActionNames.forwardAction); add(KeyEvent.VK_UP, 0, ActionNames.upAction); add(KeyEvent.VK_DOWN, 0, ActionNames.downAction); add(KeyEvent.VK_HOME, 0, ActionNames.beginLineAction); add(KeyEvent.VK_END, 0, ActionNames.endLineAction); add(KeyEvent.VK_PAGE_UP, 0, ActionNames.pageUpAction); add(KeyEvent.VK_PAGE_DOWN, 0, ActionNames.pageDownAction); add(KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK, ActionNames.nextWordAction); add(KeyEvent.VK_LEFT, InputEvent.CTRL_MASK, ActionNames.previousWordAction); add(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK, ActionNames.beginAction); add(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_MASK, ActionNames.endAction); add(KeyEvent.VK_HOME, InputEvent.CTRL_MASK, ActionNames.beginAction); add(KeyEvent.VK_END, InputEvent.CTRL_MASK, ActionNames.endAction); add(KeyEvent.VK_LEFT, InputEvent.SHIFT_MASK, ActionNames.selectionBackwardAction); add(KeyEvent.VK_RIGHT, InputEvent.SHIFT_MASK, ActionNames.selectionForwardAction); add(KeyEvent.VK_UP, InputEvent.SHIFT_MASK, ActionNames.selectionUpAction); add(KeyEvent.VK_DOWN, InputEvent.SHIFT_MASK, ActionNames.selectionDownAction); add(KeyEvent.VK_HOME, InputEvent.SHIFT_MASK, ActionNames.selectionBeginLineAction); add(KeyEvent.VK_END, InputEvent.SHIFT_MASK, ActionNames.selectionEndLineAction); add(KeyEvent.VK_PAGE_UP, InputEvent.SHIFT_MASK, ActionNames.selectionPageUpAction); add(KeyEvent.VK_PAGE_DOWN, InputEvent.SHIFT_MASK, ActionNames.selectionPageDownAction); add(KeyEvent.VK_LEFT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, ActionNames.selectionPreviousWordAction); add(KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, ActionNames.selectionNextWordAction); add(KeyEvent.VK_PAGE_UP, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, ActionNames.selectionBeginAction); add(KeyEvent.VK_PAGE_DOWN, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, ActionNames.selectionEndAction); add(KeyEvent.VK_A, InputEvent.CTRL_MASK, ActionNames.selectAllAction); add(KeyEvent.VK_INSERT, InputEvent.SHIFT_MASK, ActionNames.pasteAction); add(KeyEvent.VK_V, InputEvent.CTRL_MASK, ActionNames.pasteAction); add(KeyEvent.VK_INSERT, InputEvent.CTRL_MASK, ActionNames.copyAction); add(KeyEvent.VK_C, InputEvent.CTRL_MASK, ActionNames.copyAction); add(KeyEvent.VK_X, InputEvent.CTRL_MASK, ActionNames.cutAction); } private static void add(int vk, int mask, String actionName) { Object action = ActionSet.actionMap.get(actionName); actions.put(AWTKeyStroke.getAWTKeyStroke(vk, mask), action); } static AWTTextAction getAction(KeyEvent e) { return (AWTTextAction) actions.get(AWTKeyStroke.getAWTKeyStrokeForEvent(e)); } } protected class AccessibleAWTTextComponent extends AccessibleAWTComponent implements AccessibleText, TextListener { private static final long serialVersionUID = 3631432373506317811L; public AccessibleAWTTextComponent() { // only add this as listener TextComponent.this.addTextListener(this); } @Override public AccessibleRole getAccessibleRole() { return AccessibleRole.TEXT; } @Override public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet result = super.getAccessibleStateSet(); if (isEditable()) { result.add(AccessibleState.EDITABLE); } return result; } @Override public AccessibleText getAccessibleText() { return this; } public int getCaretPosition() { return TextComponent.this.getCaretPosition(); } public int getCharCount() { return document.getLength(); } public int getSelectionEnd() { return TextComponent.this.getSelectionEnd(); } public int getSelectionStart() { return TextComponent.this.getSelectionStart(); } public int getIndexAtPoint(Point p) { return -1; } public Rectangle getCharacterBounds(int arg0) { // TODO: implement return null; } public String getSelectedText() { String selText = TextComponent.this.getSelectedText(); return ("".equals(selText) ? null : selText); //$NON-NLS-1$ } public String getAfterIndex(int part, int index) { int offset = 0; switch (part) { case AccessibleText.CHARACTER: return (index == document.getLength()) ? null : getCharacter(index + 1); case AccessibleText.WORD: try { offset = getWordEnd(index) + 1; offset = getWordEnd(offset + 1); } catch (final BadLocationException e) { return null; } return getWord(offset); case AccessibleText.SENTENCE: // not implemented yet default: return null; } } public String getAtIndex(int part, int index) { if (document.getLength() <= 0) { return null; // compatibility } switch (part) { case AccessibleText.CHARACTER: return getCharacter(index); case AccessibleText.WORD: return getWord(index); case AccessibleText.SENTENCE: return getLine(index); default: return null; } } public String getBeforeIndex(int part, int index) { int offset = 0; switch (part) { case AccessibleText.CHARACTER: return (index == 0) ? null : getCharacter(index - 1); case AccessibleText.WORD: try { offset = getWordStart(index) - 1; offset = getWordStart(offset - 1); } catch (final BadLocationException e) { return null; } return (offset < 0) ? null : getWord(offset); case AccessibleText.SENTENCE: BreakIterator bi = BreakIterator.getSentenceInstance(); bi.setText(getText()); offset = bi.preceding(index); offset = bi.previous() + 1; return (offset < 0) ? null : getLine(offset); default: return null; } } public AttributeSet getCharacterAttribute(int arg0) { // TODO: implement return null; } public void textValueChanged(TextEvent e) { // TODO: implement } } /** * Handles key actions and updates document on * key typed events */ final class KeyHandler implements KeyListener { public void keyPressed(KeyEvent e) { performAction(e); } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { if (insertCharacter(e)) { // repaint(); } else { performAction(e); } } boolean insertCharacter(KeyEvent e) { if (!isEditable()) { return false; } char ch = e.getKeyChar(); if (Character.getType(ch) != Character.CONTROL || ch > 127) { getTextKit().replaceSelectedText(Character.toString(ch)); e.consume(); return true; } return false; } void performAction(KeyEvent e) { AWTTextAction action = KeyMap.getAction(e); if (action != null) { performTextAction(action); e.consume(); } } } /** * Handles Document changes, updates view */ final class DocumentHandler implements DocumentListener { private Rectangle getScrollPosition() { Rectangle pos = getClient(); pos.translate(scrollPosition.x, scrollPosition.y); return pos; } public void insertUpdate(DocumentEvent e) { if (getBounds().isEmpty()) { // update view only when component is "viewable" return; } getRootView().insertUpdate(e, getScrollPosition(), getRootView().getViewFactory()); updateBidiInfo(); generateEvent(); } private void updateBidiInfo() { // TODO catch BIDI chars here } public void removeUpdate(DocumentEvent e) { if (getBounds().isEmpty()) { // update view only when component is "viewable" return; } getRootView().removeUpdate(e, getScrollPosition(), getRootView().getViewFactory()); generateEvent(); } public void changedUpdate(DocumentEvent e) { if (getBounds().isEmpty()) { // update view only when component is "viewable" return; } getRootView().changedUpdate(e, getScrollPosition(), getRootView().getViewFactory()); generateEvent(); } View getRootView() { return rootViewContext.getView(); } } /** * Implements all necessary document/view/caret operations for text handling */ class TextKitImpl implements TextKit, ViewFactory, RootViewContext.ViewFactoryGetter { public boolean isEditable() { return TextComponent.this.isEditable(); } public void replaceSelectedText(String text) { int dot = caret.getDot(); int mark = caret.getMark(); try { int start = Math.min(dot, mark); int length = Math.abs(dot - mark); synchronized(TextComponent.this) { document.replace(start, length, text, null); } } catch (final BadLocationException e) { } } public TextCaret getCaret() { return caret; } public Document getDocument() { return document; } public String getSelectedText() { String s = null; int dot = caret.getDot(); int mark = caret.getMark(); if (dot == mark) { return null; } try { s = document.getText(Math.min(dot, mark), Math.abs(dot - mark)); } catch (final BadLocationException e) { } return s; } public int getSelectionStart() { return Math.min(caret.getDot(), caret.getMark()); } public int getSelectionEnd() { return Math.max(caret.getDot(), caret.getMark()); } public Rectangle getVisibleRect() { return new Rectangle(-scrollPosition.x, -scrollPosition.y, w, h); } public View getRootView() { return rootViewContext.getView(); } public Rectangle modelToView(int pos) throws BadLocationException { return modelToView(pos, Bias.Forward); } public Rectangle modelToView(int pos, Bias bias) throws BadLocationException { Rectangle mRect = getModelRect(); if (mRect.isEmpty()) { return null; } Shape shape = getRootView().modelToView(pos, mRect, bias); if (shape != null) { return shape.getBounds(); } return null; } public Component getComponent() { return TextComponent.this; } public int viewToModel(Point p, Bias[] biasRet) { return getRootView().viewToModel(p.x, p.y, getModelRect(), biasRet); } public void scrollRectToVisible(Rectangle rect) { TextComponent.this.scrollRectToVisible(rect); } public boolean isScrollBarArea(int x, int y) { return false; } public void addCaretListeners(EventListener listener) { // do nothing } public void paintLayeredHighlights(Graphics g, int p0, int p1, Shape shape, View view) { caret.getHighlighter().paintLayeredHighlights(g, p0, p1, shape, view); } public void revalidate() { TextComponent.this.revalidate(); } public Color getDisabledTextColor() { return SystemColor.textInactiveText; } public Color getSelectedTextColor() { return SystemColor.textHighlightText; } public View create(Element element) { // do nothing return null; } public ViewFactory getViewFactory() { return this; } } class State extends Component.ComponentState implements TextComponentState { final Dimension textSize = new Dimension(); public String getText() { return TextComponent.this.getText(); } public Dimension getTextSize() { return textSize; } public void setTextSize(Dimension size) { textSize.setSize(size); } @Override public boolean isEnabled() { return super.isEnabled() && isEditable(); } public Rectangle getClient() { return TextComponent.this.getClient(); } public Insets getInsets() { return getNativeInsets(); } } protected volatile transient TextListener textListener; private final AWTListenerList<TextListener> textListeners = new AWTListenerList<TextListener>( this); AbstractDocument document; final transient TextCaret caret; final transient RootViewContext rootViewContext; final Point scrollPosition = new Point(); private boolean editable; private final Insets BORDER = new Insets(2, 2, 2, 2); private final State state; TextComponent() { state = new State(); editable = true; dispatchToIM = true; // had been disabled by createBehavior() setFont(new Font("DialogInput", Font.PLAIN, 12)); // QUICK FIX //$NON-NLS-1$ document = new PlainDocument(); // text = new StringBuffer(); setTextKit(new TextKitImpl()); rootViewContext = createRootViewContext(); rootViewContext.getView().append(createView()); rootViewContext.getView().setSize(w, h); caret = createCaret(); setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); addAWTMouseListener(getMouseHandler()); addAWTMouseMotionListener(getMotionHandler()); addAWTFocusListener((FocusListener) caret); addAWTKeyListener(new KeyHandler()); // document handler must be added after caret's listener has been added! document.addDocumentListener(new DocumentHandler()); } /** * Gets current mouse motion events handler. * To be overridden. */ MouseMotionListener getMotionHandler() { return (MouseMotionListener) caret; } /** * Gets current mouse events handler. * To be overridden. */ MouseListener getMouseHandler() { return (MouseListener) caret; } /** * Re-calculates internal layout, repaints component */ void revalidate() { // to be overridden by TextArea invalidate(); validate(); repaint(); } /** * Creates and initializes root view associated with this * TextComponent, document, text kit. * @return this component's root view */ private RootViewContext createRootViewContext() { TextFactory factory = TextFactory.getTextFactory(); RootViewContext c = factory.createRootView(null); c.setComponent(this); c.setDocument(document); c.setViewFactoryGetter((TextKitImpl) getTextKit()); return c; } /** * Creates default plain view */ View createView() { TextFactory factory = TextFactory.getTextFactory(); View v = factory.createPlainView(document.getDefaultRootElement()); return v; } /** * @return new text caret associated with this TextComponent */ TextCaret createCaret() { TextFactory factory = TextFactory.getTextFactory(); TextCaret c = factory.createCaret(); c.setComponent(this); return c; } @Override ComponentBehavior createBehavior() { return new HWBehavior(this); } @Override public void addNotify() { // toolkit.lockAWT(); // try { super.addNotify(); // } finally { // toolkit.unlockAWT(); // } // ajust caret position if was invalid int maxPos = document.getLength(); if (getCaretPosition() > maxPos) { caret.setDot(maxPos, caret.getDotBias()); } } @Override public AccessibleContext getAccessibleContext() { toolkit.lockAWT(); try { return super.getAccessibleContext(); } finally { toolkit.unlockAWT(); } } public String getText() { toolkit.lockAWT(); try { return document.getText(0, document.getLength()); } catch (BadLocationException e) { return ""; //$NON-NLS-1$ } finally { toolkit.unlockAWT(); } } @Override protected String paramString() { /* The format is based on 1.5 release behavior * which can be revealed by the following code: * System.out.println(new TextField()); */ toolkit.lockAWT(); try { return (super.paramString() + ",text=" + getText() //$NON-NLS-1$ + (isEditable() ? ",editable" : "") + ",selection=" + getSelectionStart() //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "-" + getSelectionEnd()); //$NON-NLS-1$ } finally { toolkit.unlockAWT(); } } @Override public void enableInputMethods(boolean enable) { toolkit.lockAWT(); try { // TODO: implement super.enableInputMethods(enable); } finally { toolkit.unlockAWT(); } } @Override public Color getBackground() { toolkit.lockAWT(); try { if (isDisplayable() && !isBackgroundSet()) { return (isEditable() ? SystemColor.window : SystemColor.control); } return super.getBackground(); } finally { toolkit.unlockAWT(); } } public int getCaretPosition() { toolkit.lockAWT(); try { return caret.getDot(); } finally { toolkit.unlockAWT(); } } public String getSelectedText() { toolkit.lockAWT(); try { String s = null; try { int length = getSelectionEnd() - getSelectionStart(); s = document.getText(getSelectionStart(), length); } catch (final BadLocationException e) { } return s; } finally { toolkit.unlockAWT(); } } public int getSelectionEnd() { toolkit.lockAWT(); try { return Math.max(caret.getDot(), caret.getMark()); } finally { toolkit.unlockAWT(); } } public int getSelectionStart() { toolkit.lockAWT(); try { return Math.min(caret.getDot(), caret.getMark()); } finally { toolkit.unlockAWT(); } } public boolean isEditable() { toolkit.lockAWT(); try { return editable; } finally { toolkit.unlockAWT(); } } @Override public void removeNotify() { toolkit.lockAWT(); try { super.removeNotify(); } finally { toolkit.unlockAWT(); } } public void select(int selectionStart, int selectionEnd) { toolkit.lockAWT(); try { setSelectionEnd(selectionEnd); setSelectionStart(selectionStart); } finally { toolkit.unlockAWT(); } } public void selectAll() { toolkit.lockAWT(); try { select(0, document.getLength()); } finally { toolkit.unlockAWT(); } } @Override public void setBackground(Color c) { toolkit.lockAWT(); try { super.setBackground(c); } finally { toolkit.unlockAWT(); } } public void setCaretPosition(int position) { toolkit.lockAWT(); try { if (position < 0) { // awt.101=position less than zero. throw new IllegalArgumentException(Messages.getString("awt.101")); //$NON-NLS-1$ } position = Math.min(document.getLength(), position); } finally { toolkit.unlockAWT(); } caret.setDot(position, caret.getDotBias()); } public void setEditable(boolean b) { toolkit.lockAWT(); try { if (editable != b) { // to avoid dead loop in repaint() editable = b; repaint(); // background color changes } } finally { toolkit.unlockAWT(); } } public void setSelectionEnd(int selectionEnd) { // toolkit.lockAWT(); // try { selectionEnd = Math.min(selectionEnd, document.getLength()); int start = getSelectionStart(); if (selectionEnd < start) { caret.setDot(selectionEnd, caret.getDotBias()); } else { caret.setDot(start, caret.getDotBias()); caret.moveDot(Math.max(start, selectionEnd), caret.getDotBias()); } // } finally { // toolkit.unlockAWT(); // } } public void setSelectionStart(int selectionStart) { // toolkit.lockAWT(); // try { selectionStart = Math.max(selectionStart, 0); int end = getSelectionEnd(); if (selectionStart > end) { caret.setDot(selectionStart, caret.getDotBias()); } else { caret.setDot(end, caret.getDotBias()); caret.moveDot(Math.min(end, selectionStart), caret.getDotBias()); } // } finally { // toolkit.unlockAWT(); // } } public void setText(String text) { toolkit.lockAWT(); try { if (text == null) { text = ""; //$NON-NLS-1$ } } finally { toolkit.unlockAWT(); } try { if (isDisplayable()) { // reset position to 0 if was displayable caret.setDot(0, caret.getDotBias()); } int oldCaretPos = caret.getDot(); synchronized (this) { document.replace(0, document.getLength(), text, null); } if (!isDisplayable() && (oldCaretPos != caret.getDot())) { // return caret back to emulate "no movement" caret.setDot(oldCaretPos, caret.getDotBias()); } } catch (BadLocationException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") @Override public <T extends EventListener> T[] getListeners(Class<T> listenerType) { if (TextListener.class.isAssignableFrom(listenerType)) { return (T[]) getTextListeners(); } return super.getListeners(listenerType); } public void addTextListener(TextListener l) { textListeners.addUserListener(l); // for compatibility only: textListener = AWTEventMulticaster.add(textListener, l); } public void removeTextListener(TextListener l) { textListeners.removeUserListener(l); // for compatibility only: textListener = AWTEventMulticaster.remove(textListener, l); } public TextListener[] getTextListeners() { return textListeners.getUserListeners(new TextListener[0]); } @Override protected void processEvent(AWTEvent e) { if (toolkit.eventTypeLookup.getEventMask(e) == AWTEvent.TEXT_EVENT_MASK) { processTextEvent((TextEvent) e); } else { super.processEvent(e); } } protected void processTextEvent(TextEvent e) { for (TextListener listener : textListeners.getUserListeners()) { switch (e.getID()) { case TextEvent.TEXT_VALUE_CHANGED: listener.textValueChanged(e); break; } } } /** * Calculates and sets new scroll position * to make rectangle visible * @param r rectangle to make visible by * scrolling */ void scrollRectToVisible(final Rectangle r) { Point viewPos = getViewPosition(); Insets ins = getInsets(); Dimension viewSize = getClient().getSize(); if ((viewSize.height <= 0) || (viewSize.width <= 0)) { return; // FIX } int dx; int dy; r.x -= ins.left; r.y -= ins.top; if (r.x > 0) { if (r.x + r.width > viewSize.width) { int dx2 = r.x + r.width - viewSize.width; dx = Math.min(r.x, dx2); } else { dx = 0; } } else if (r.x < 0) { if (r.x + r.width < viewSize.width) { int dx2 = r.x + r.width - viewSize.width; dx = Math.max(r.x, dx2); } else { dx = 0; } } else { dx = 0; } if (r.y > 0) { if (r.y + r.height > viewSize.height) { int dy2 = r.y + r.height - viewSize.height; dy = Math.min(r.y, dy2); } else { dy = 0; } } else if (r.y < 0) { if (r.y + r.height < viewSize.height) { int dy2 = r.y + r.height - viewSize.height; dy = Math.max(r.y, dy2); } else { dy = 0; } } else { dy = 0; } if (dx != 0 || dy != 0) { int x = viewPos.x + dx; int y = viewPos.y + dy; Point point = new Point(x, y); setViewPosition(point); repaint(); } } /** * Sets new scroll position * @param point scroll position to set */ void setViewPosition(Point point) { scrollPosition.setLocation(-point.x, -point.y); } /** * Gets current scroll position */ Point getViewPosition() { return new Point(-scrollPosition.x, -scrollPosition.y); } Rectangle getClient() { Insets insets = getInsets(); return new Rectangle(insets.left, insets.top, w - insets.right - insets.left, h - insets.top - insets.bottom); } /** * Gets the rectangle with height required to hold all text * and width equal to component's client width(only visible * part of text fits this width) */ Rectangle getModelRect() { Rectangle clientRect = getClient(); clientRect.translate(scrollPosition.x, scrollPosition.y); View view = rootViewContext.getView(); int ySpan = (int) view.getPreferredSpan(View.Y_AXIS); clientRect.height = ySpan; return clientRect; } private void generateEvent() { postEvent(new TextEvent(this, TextEvent.TEXT_VALUE_CHANGED)); } @Override void prepaint(Graphics g) { toolkit.theme.drawTextComponentBackground(g, state); g.setFont(getFont()); g.setColor(isEnabled() ? getForeground() : SystemColor.textInactiveText); Rectangle r = getModelRect(); rootViewContext.getView().setSize(r.width, r.height); Rectangle client = getClient(); Shape oldClip = g.getClip(); g.clipRect(client.x, client.y, client.width, client.height); document.readLock(); try { rootViewContext.getView().paint(g, r); caret.paint(g); } finally { document.readUnlock(); } g.setClip(oldClip); } @Override Insets getNativeInsets() { return (Insets) BORDER.clone(); } @Override Insets getInsets() { // to be overridden by TextArea return getNativeInsets(); } @Override AccessibleContext createAccessibleContext() { return new AccessibleAWTTextComponent(); } private String getLine(int index) { String result = null; BreakIterator bi = BreakIterator.getSentenceInstance(); bi.setText(getText()); int end = bi.following(index); int start = bi.preceding(end - 1); try { result = document.getText(start, end - start); } catch (BadLocationException e) { e.printStackTrace(); } return result; } private String getWord(int index) { int start = 0; int length = 0; String result = null; try { start = getWordStart(index); length = getWordEnd(index) - start; result = document.getText(start, length); } catch (final BadLocationException e) { } return result; } private String getCharacter(int index) { String s = null; try { s = document.getText(index, 1); } catch (final BadLocationException e) { } return s; } private int getWordEnd(final int pos) throws BadLocationException { BreakIterator bi = BreakIterator.getWordInstance(); int length = document.getLength(); if (pos < 0 || pos > length) { // awt.2B=No word at {0} throwException(Messages.getString("awt.2B", pos), pos); //$NON-NLS-1$ } String content = document.getText(0, length); bi.setText(content); return (pos < bi.last()) ? bi.following(pos) : pos; } private int getWordStart(final int pos) throws BadLocationException { BreakIterator bi = BreakIterator.getWordInstance(); int length = document.getLength(); if (pos < 0 || pos > length) { // awt.2B=No word at {0} throwException(Messages.getString("awt.2B", pos), pos); //$NON-NLS-1$ } String content = null; content = document.getText(0, length); bi.setText(content); int iteratorWordStart = pos; if (pos < length - 1) { iteratorWordStart = bi.preceding(pos + 1); } else { bi.last(); iteratorWordStart = bi.previous(); } return iteratorWordStart; } private static void throwException(final String s, final int i) throws BadLocationException { throw new BadLocationException(s, i); } @Override void setEnabledImpl(boolean value) { if (value != isEnabled()) { // to avoid dead loop in repaint() super.setEnabledImpl(value); if (isShowing()) { repaint(); } } } @Override void postprocessEvent(AWTEvent e, long eventMask) { // have to call system listeners without AWT lock // to avoid deadlocks in code common with UI text if (eventMask == AWTEvent.FOCUS_EVENT_MASK) { preprocessFocusEvent((FocusEvent) e); } else if (eventMask == AWTEvent.KEY_EVENT_MASK) { preprocessKeyEvent((KeyEvent) e); } else if (eventMask == AWTEvent.MOUSE_EVENT_MASK) { preprocessMouseEvent((MouseEvent) e); } else if (eventMask == AWTEvent.MOUSE_MOTION_EVENT_MASK) { preprocessMouseMotionEvent((MouseEvent) e); } else { super.postprocessEvent(e, eventMask); } } void performTextAction(AWTTextAction action) { action.performAction(getTextKit()); } }
google/j2objc
36,718
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/chrono/ChronoLocalDate.java
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package java.time.chrono; import static java.time.temporal.ChronoField.EPOCH_DAY; import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoUnit.DAYS; import java.io.Serializable; import java.time.DateTimeException; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; import java.time.temporal.TemporalQuery; import java.time.temporal.TemporalUnit; import java.time.temporal.UnsupportedTemporalTypeException; import java.util.Comparator; import java.util.Objects; /** * A date without time-of-day or time-zone in an arbitrary chronology, intended * for advanced globalization use cases. * <p> * <b>Most applications should declare method signatures, fields and variables * as {@link LocalDate}, not this interface.</b> * <p> * A {@code ChronoLocalDate} is the abstract representation of a date where the * {@code Chronology chronology}, or calendar system, is pluggable. * The date is defined in terms of fields expressed by {@link TemporalField}, * where most common implementations are defined in {@link ChronoField}. * The chronology defines how the calendar system operates and the meaning of * the standard fields. * * <h3>When to use this interface</h3> * The design of the API encourages the use of {@code LocalDate} rather than this * interface, even in the case where the application needs to deal with multiple * calendar systems. * <p> * This concept can seem surprising at first, as the natural way to globalize an * application might initially appear to be to abstract the calendar system. * However, as explored below, abstracting the calendar system is usually the wrong * approach, resulting in logic errors and hard to find bugs. * As such, it should be considered an application-wide architectural decision to choose * to use this interface as opposed to {@code LocalDate}. * * <h3>Architectural issues to consider</h3> * These are some of the points that must be considered before using this interface * throughout an application. * <p> * 1) Applications using this interface, as opposed to using just {@code LocalDate}, * face a significantly higher probability of bugs. This is because the calendar system * in use is not known at development time. A key cause of bugs is where the developer * applies assumptions from their day-to-day knowledge of the ISO calendar system * to code that is intended to deal with any arbitrary calendar system. * The section below outlines how those assumptions can cause problems * The primary mechanism for reducing this increased risk of bugs is a strong code review process. * This should also be considered a extra cost in maintenance for the lifetime of the code. * <p> * 2) This interface does not enforce immutability of implementations. * While the implementation notes indicate that all implementations must be immutable * there is nothing in the code or type system to enforce this. Any method declared * to accept a {@code ChronoLocalDate} could therefore be passed a poorly or * maliciously written mutable implementation. * <p> * 3) Applications using this interface must consider the impact of eras. * {@code LocalDate} shields users from the concept of eras, by ensuring that {@code getYear()} * returns the proleptic year. That decision ensures that developers can think of * {@code LocalDate} instances as consisting of three fields - year, month-of-year and day-of-month. * By contrast, users of this interface must think of dates as consisting of four fields - * era, year-of-era, month-of-year and day-of-month. The extra era field is frequently * forgotten, yet it is of vital importance to dates in an arbitrary calendar system. * For example, in the Japanese calendar system, the era represents the reign of an Emperor. * Whenever one reign ends and another starts, the year-of-era is reset to one. * <p> * 4) The only agreed international standard for passing a date between two systems * is the ISO-8601 standard which requires the ISO calendar system. Using this interface * throughout the application will inevitably lead to the requirement to pass the date * across a network or component boundary, requiring an application specific protocol or format. * <p> * 5) Long term persistence, such as a database, will almost always only accept dates in the * ISO-8601 calendar system (or the related Julian-Gregorian). Passing around dates in other * calendar systems increases the complications of interacting with persistence. * <p> * 6) Most of the time, passing a {@code ChronoLocalDate} throughout an application * is unnecessary, as discussed in the last section below. * * <h3>False assumptions causing bugs in multi-calendar system code</h3> * As indicated above, there are many issues to consider when try to use and manipulate a * date in an arbitrary calendar system. These are some of the key issues. * <p> * Code that queries the day-of-month and assumes that the value will never be more than * 31 is invalid. Some calendar systems have more than 31 days in some months. * <p> * Code that adds 12 months to a date and assumes that a year has been added is invalid. * Some calendar systems have a different number of months, such as 13 in the Coptic or Ethiopic. * <p> * Code that adds one month to a date and assumes that the month-of-year value will increase * by one or wrap to the next year is invalid. Some calendar systems have a variable number * of months in a year, such as the Hebrew. * <p> * Code that adds one month, then adds a second one month and assumes that the day-of-month * will remain close to its original value is invalid. Some calendar systems have a large difference * between the length of the longest month and the length of the shortest month. * For example, the Coptic or Ethiopic have 12 months of 30 days and 1 month of 5 days. * <p> * Code that adds seven days and assumes that a week has been added is invalid. * Some calendar systems have weeks of other than seven days, such as the French Revolutionary. * <p> * Code that assumes that because the year of {@code date1} is greater than the year of {@code date2} * then {@code date1} is after {@code date2} is invalid. This is invalid for all calendar systems * when referring to the year-of-era, and especially untrue of the Japanese calendar system * where the year-of-era restarts with the reign of every new Emperor. * <p> * Code that treats month-of-year one and day-of-month one as the start of the year is invalid. * Not all calendar systems start the year when the month value is one. * <p> * In general, manipulating a date, and even querying a date, is wide open to bugs when the * calendar system is unknown at development time. This is why it is essential that code using * this interface is subjected to additional code reviews. It is also why an architectural * decision to avoid this interface type is usually the correct one. * * <h3>Using LocalDate instead</h3> * The primary alternative to using this interface throughout your application is as follows. * <ul> * <li>Declare all method signatures referring to dates in terms of {@code LocalDate}. * <li>Either store the chronology (calendar system) in the user profile or lookup * the chronology from the user locale * <li>Convert the ISO {@code LocalDate} to and from the user's preferred calendar system during * printing and parsing * </ul> * This approach treats the problem of globalized calendar systems as a localization issue * and confines it to the UI layer. This approach is in keeping with other localization * issues in the java platform. * <p> * As discussed above, performing calculations on a date where the rules of the calendar system * are pluggable requires skill and is not recommended. * Fortunately, the need to perform calculations on a date in an arbitrary calendar system * is extremely rare. For example, it is highly unlikely that the business rules of a library * book rental scheme will allow rentals to be for one month, where meaning of the month * is dependent on the user's preferred calendar system. * <p> * A key use case for calculations on a date in an arbitrary calendar system is producing * a month-by-month calendar for display and user interaction. Again, this is a UI issue, * and use of this interface solely within a few methods of the UI layer may be justified. * <p> * In any other part of the system, where a date must be manipulated in a calendar system * other than ISO, the use case will generally specify the calendar system to use. * For example, an application may need to calculate the next Islamic or Hebrew holiday * which may require manipulating the date. * This kind of use case can be handled as follows: * <ul> * <li>start from the ISO {@code LocalDate} being passed to the method * <li>convert the date to the alternate calendar system, which for this use case is known * rather than arbitrary * <li>perform the calculation * <li>convert back to {@code LocalDate} * </ul> * Developers writing low-level frameworks or libraries should also avoid this interface. * Instead, one of the two general purpose access interfaces should be used. * Use {@link TemporalAccessor} if read-only access is required, or use {@link Temporal} * if read-write access is required. * * @implSpec * This interface must be implemented with care to ensure other classes operate correctly. * All implementations that can be instantiated must be final, immutable and thread-safe. * Subclasses should be Serializable wherever possible. * <p> * Additional calendar systems may be added to the system. * See {@link Chronology} for more details. * * @since 1.8 */ public interface ChronoLocalDate extends Temporal, TemporalAdjuster, Comparable<ChronoLocalDate> { /** * Gets a comparator that compares {@code ChronoLocalDate} in * time-line order ignoring the chronology. * <p> * This comparator differs from the comparison in {@link #compareTo} in that it * only compares the underlying date and not the chronology. * This allows dates in different calendar systems to be compared based * on the position of the date on the local time-line. * The underlying comparison is equivalent to comparing the epoch-day. * * @return a comparator that compares in time-line order ignoring the chronology * @see #isAfter * @see #isBefore * @see #isEqual */ static Comparator<ChronoLocalDate> timeLineOrder() { return (Comparator<ChronoLocalDate> & Serializable) (date1, date2) -> { return Long.compare(date1.toEpochDay(), date2.toEpochDay()); }; } //----------------------------------------------------------------------- /** * Obtains an instance of {@code ChronoLocalDate} from a temporal object. * <p> * This obtains a local date based on the specified temporal. * A {@code TemporalAccessor} represents an arbitrary set of date and time information, * which this factory converts to an instance of {@code ChronoLocalDate}. * <p> * The conversion extracts and combines the chronology and the date * from the temporal object. The behavior is equivalent to using * {@link Chronology#date(TemporalAccessor)} with the extracted chronology. * Implementations are permitted to perform optimizations such as accessing * those fields that are equivalent to the relevant objects. * <p> * This method matches the signature of the functional interface {@link TemporalQuery} * allowing it to be used as a query via method reference, {@code ChronoLocalDate::from}. * * @param temporal the temporal object to convert, not null * @return the date, not null * @throws DateTimeException if unable to convert to a {@code ChronoLocalDate} * @see Chronology#date(TemporalAccessor) */ static ChronoLocalDate from(TemporalAccessor temporal) { if (temporal instanceof ChronoLocalDate) { return (ChronoLocalDate) temporal; } Objects.requireNonNull(temporal, "temporal"); Chronology chrono = temporal.query(TemporalQueries.chronology()); if (chrono == null) { throw new DateTimeException( "Unable to obtain ChronoLocalDate from TemporalAccessor: " + temporal.getClass()); } return chrono.date(temporal); } //----------------------------------------------------------------------- /** * Gets the chronology of this date. * <p> * The {@code Chronology} represents the calendar system in use. * The era and other fields in {@link ChronoField} are defined by the chronology. * * @return the chronology, not null */ Chronology getChronology(); /** * Gets the era, as defined by the chronology. * <p> * The era is, conceptually, the largest division of the time-line. * Most calendar systems have a single epoch dividing the time-line into two eras. * However, some have multiple eras, such as one for the reign of each leader. * The exact meaning is determined by the {@code Chronology}. * <p> * All correctly implemented {@code Era} classes are singletons, thus it * is valid code to write {@code date.getEra() == SomeChrono.ERA_NAME)}. * <p> * This default implementation uses {@link Chronology#eraOf(int)}. * * @return the chronology specific era constant applicable at this date, not null */ default Era getEra() { return getChronology().eraOf(get(ERA)); } /** * Checks if the year is a leap year, as defined by the calendar system. * <p> * A leap-year is a year of a longer length than normal. * The exact meaning is determined by the chronology with the constraint that * a leap-year must imply a year-length longer than a non leap-year. * <p> * This default implementation uses {@link Chronology#isLeapYear(long)}. * * @return true if this date is in a leap year, false otherwise */ default boolean isLeapYear() { return getChronology().isLeapYear(getLong(YEAR)); } /** * Returns the length of the month represented by this date, as defined by the calendar system. * <p> * This returns the length of the month in days. * * @return the length of the month in days */ int lengthOfMonth(); /** * Returns the length of the year represented by this date, as defined by the calendar system. * <p> * This returns the length of the year in days. * <p> * The default implementation uses {@link #isLeapYear()} and returns 365 or 366. * * @return the length of the year in days */ default int lengthOfYear() { return (isLeapYear() ? 366 : 365); } /** * Checks if the specified field is supported. * <p> * This checks if the specified field can be queried on this date. * If false, then calling the {@link #range(TemporalField) range}, * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} * methods will throw an exception. * <p> * The set of supported fields is defined by the chronology and normally includes * all {@code ChronoField} date fields. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} * passing {@code this} as the argument. * Whether the field is supported is determined by the field. * * @param field the field to check, null returns false * @return true if the field can be queried, false if not */ @Override default boolean isSupported(TemporalField field) { if (field instanceof ChronoField) { return field.isDateBased(); } return field != null && field.isSupportedBy(this); } /** * Checks if the specified unit is supported. * <p> * This checks if the specified unit can be added to or subtracted from this date. * If false, then calling the {@link #plus(long, TemporalUnit)} and * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. * <p> * The set of supported units is defined by the chronology and normally includes * all {@code ChronoUnit} date units except {@code FOREVER}. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} * passing {@code this} as the argument. * Whether the unit is supported is determined by the unit. * * @param unit the unit to check, null returns false * @return true if the unit can be added/subtracted, false if not */ @Override default boolean isSupported(TemporalUnit unit) { if (unit instanceof ChronoUnit) { return unit.isDateBased(); } return unit != null && unit.isSupportedBy(this); } //----------------------------------------------------------------------- // override for covariant return type /** * {@inheritDoc} * @throws DateTimeException {@inheritDoc} * @throws ArithmeticException {@inheritDoc} */ @Override default ChronoLocalDate with(TemporalAdjuster adjuster) { return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.with(adjuster)); } /** * {@inheritDoc} * @throws DateTimeException {@inheritDoc} * @throws UnsupportedTemporalTypeException {@inheritDoc} * @throws ArithmeticException {@inheritDoc} */ @Override default ChronoLocalDate with(TemporalField field, long newValue) { if (field instanceof ChronoField) { throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } return ChronoLocalDateImpl.ensureValid(getChronology(), field.adjustInto(this, newValue)); } /** * {@inheritDoc} * @throws DateTimeException {@inheritDoc} * @throws ArithmeticException {@inheritDoc} */ @Override default ChronoLocalDate plus(TemporalAmount amount) { return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.plus(amount)); } /** * {@inheritDoc} * @throws DateTimeException {@inheritDoc} * @throws ArithmeticException {@inheritDoc} */ @Override default ChronoLocalDate plus(long amountToAdd, TemporalUnit unit) { if (unit instanceof ChronoUnit) { throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } return ChronoLocalDateImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd)); } /** * {@inheritDoc} * @throws DateTimeException {@inheritDoc} * @throws ArithmeticException {@inheritDoc} */ @Override default ChronoLocalDate minus(TemporalAmount amount) { return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.minus(amount)); } /** * {@inheritDoc} * @throws DateTimeException {@inheritDoc} * @throws UnsupportedTemporalTypeException {@inheritDoc} * @throws ArithmeticException {@inheritDoc} */ @Override default ChronoLocalDate minus(long amountToSubtract, TemporalUnit unit) { return ChronoLocalDateImpl.ensureValid(getChronology(), Temporal.super.minus(amountToSubtract, unit)); } //----------------------------------------------------------------------- /** * Queries this date using the specified query. * <p> * This queries this date using the specified query strategy object. * The {@code TemporalQuery} object defines the logic to be used to * obtain the result. Read the documentation of the query to understand * what the result of this method will be. * <p> * The result of this method is obtained by invoking the * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the * specified query passing {@code this} as the argument. * * @param <R> the type of the result * @param query the query to invoke, not null * @return the query result, null may be returned (defined by the query) * @throws DateTimeException if unable to query (defined by the query) * @throws ArithmeticException if numeric overflow occurs (defined by the query) */ @SuppressWarnings("unchecked") @Override default <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.zoneId() || query == TemporalQueries.zone() || query == TemporalQueries.offset()) { return null; } else if (query == TemporalQueries.localTime()) { return null; } else if (query == TemporalQueries.chronology()) { return (R) getChronology(); } else if (query == TemporalQueries.precision()) { return (R) DAYS; } // inline TemporalAccessor.super.query(query) as an optimization // non-JDK classes are not permitted to make this optimization return query.queryFrom(this); } /** * Adjusts the specified temporal object to have the same date as this object. * <p> * This returns a temporal object of the same observable type as the input * with the date changed to be the same as this. * <p> * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} * passing {@link ChronoField#EPOCH_DAY} as the field. * <p> * In most cases, it is clearer to reverse the calling pattern by using * {@link Temporal#with(TemporalAdjuster)}: * <pre> * // these two lines are equivalent, but the second approach is recommended * temporal = thisLocalDate.adjustInto(temporal); * temporal = temporal.with(thisLocalDate); * </pre> * <p> * This instance is immutable and unaffected by this method call. * * @param temporal the target object to be adjusted, not null * @return the adjusted object, not null * @throws DateTimeException if unable to make the adjustment * @throws ArithmeticException if numeric overflow occurs */ @Override default Temporal adjustInto(Temporal temporal) { return temporal.with(EPOCH_DAY, toEpochDay()); } /** * Calculates the amount of time until another date in terms of the specified unit. * <p> * This calculates the amount of time between two {@code ChronoLocalDate} * objects in terms of a single {@code TemporalUnit}. * The start and end points are {@code this} and the specified date. * The result will be negative if the end is before the start. * The {@code Temporal} passed to this method is converted to a * {@code ChronoLocalDate} using {@link Chronology#date(TemporalAccessor)}. * The calculation returns a whole number, representing the number of * complete units between the two dates. * For example, the amount in days between two dates can be calculated * using {@code startDate.until(endDate, DAYS)}. * <p> * There are two equivalent ways of using this method. * The first is to invoke this method. * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: * <pre> * // these two lines are equivalent * amount = start.until(end, MONTHS); * amount = MONTHS.between(start, end); * </pre> * The choice should be made based on which makes the code more readable. * <p> * The calculation is implemented in this method for {@link ChronoUnit}. * The units {@code DAYS}, {@code WEEKS}, {@code MONTHS}, {@code YEARS}, * {@code DECADES}, {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} * should be supported by all implementations. * Other {@code ChronoUnit} values will throw an exception. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} * passing {@code this} as the first argument and the converted input temporal as * the second argument. * <p> * This instance is immutable and unaffected by this method call. * * @param endExclusive the end date, exclusive, which is converted to a * {@code ChronoLocalDate} in the same chronology, not null * @param unit the unit to measure the amount in, not null * @return the amount of time between this date and the end date * @throws DateTimeException if the amount cannot be calculated, or the end * temporal cannot be converted to a {@code ChronoLocalDate} * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override // override for Javadoc long until(Temporal endExclusive, TemporalUnit unit); /** * Calculates the period between this date and another date as a {@code ChronoPeriod}. * <p> * This calculates the period between two dates. All supplied chronologies * calculate the period using years, months and days, however the * {@code ChronoPeriod} API allows the period to be represented using other units. * <p> * The start and end points are {@code this} and the specified date. * The result will be negative if the end is before the start. * The negative sign will be the same in each of year, month and day. * <p> * The calculation is performed using the chronology of this date. * If necessary, the input date will be converted to match. * <p> * This instance is immutable and unaffected by this method call. * * @param endDateExclusive the end date, exclusive, which may be in any chronology, not null * @return the period between this date and the end date, not null * @throws DateTimeException if the period cannot be calculated * @throws ArithmeticException if numeric overflow occurs */ ChronoPeriod until(ChronoLocalDate endDateExclusive); /** * Formats this date using the specified formatter. * <p> * This date will be passed to the formatter to produce a string. * <p> * The default implementation must behave as follows: * <pre> * return formatter.format(this); * </pre> * * @param formatter the formatter to use, not null * @return the formatted date string, not null * @throws DateTimeException if an error occurs during printing */ default String format(DateTimeFormatter formatter) { Objects.requireNonNull(formatter, "formatter"); return formatter.format(this); } //----------------------------------------------------------------------- /** * Combines this date with a time to create a {@code ChronoLocalDateTime}. * <p> * This returns a {@code ChronoLocalDateTime} formed from this date at the specified time. * All possible combinations of date and time are valid. * * @param localTime the local time to use, not null * @return the local date-time formed from this date and the specified time, not null */ @SuppressWarnings("unchecked") default ChronoLocalDateTime<?> atTime(LocalTime localTime) { return ChronoLocalDateTimeImpl.of(this, localTime); } //----------------------------------------------------------------------- /** * Converts this date to the Epoch Day. * <p> * The {@link ChronoField#EPOCH_DAY Epoch Day count} is a simple * incrementing count of days where day 0 is 1970-01-01 (ISO). * This definition is the same for all chronologies, enabling conversion. * <p> * This default implementation queries the {@code EPOCH_DAY} field. * * @return the Epoch Day equivalent to this date */ default long toEpochDay() { return getLong(EPOCH_DAY); } //----------------------------------------------------------------------- /** * Compares this date to another date, including the chronology. * <p> * The comparison is based first on the underlying time-line date, then * on the chronology. * It is "consistent with equals", as defined by {@link Comparable}. * <p> * For example, the following is the comparator order: * <ol> * <li>{@code 2012-12-03 (ISO)}</li> * <li>{@code 2012-12-04 (ISO)}</li> * <li>{@code 2555-12-04 (ThaiBuddhist)}</li> * <li>{@code 2012-12-05 (ISO)}</li> * </ol> * Values #2 and #3 represent the same date on the time-line. * When two values represent the same date, the chronology ID is compared to distinguish them. * This step is needed to make the ordering "consistent with equals". * <p> * If all the date objects being compared are in the same chronology, then the * additional chronology stage is not required and only the local date is used. * To compare the dates of two {@code TemporalAccessor} instances, including dates * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator. * <p> * This default implementation performs the comparison defined above. * * @param other the other date to compare to, not null * @return the comparator value, negative if less, positive if greater */ @Override default int compareTo(ChronoLocalDate other) { int cmp = Long.compare(toEpochDay(), other.toEpochDay()); if (cmp == 0) { cmp = getChronology().compareTo(other.getChronology()); } return cmp; } /** * Checks if this date is after the specified date ignoring the chronology. * <p> * This method differs from the comparison in {@link #compareTo} in that it * only compares the underlying date and not the chronology. * This allows dates in different calendar systems to be compared based * on the time-line position. * This is equivalent to using {@code date1.toEpochDay() > date2.toEpochDay()}. * <p> * This default implementation performs the comparison based on the epoch-day. * * @param other the other date to compare to, not null * @return true if this is after the specified date */ default boolean isAfter(ChronoLocalDate other) { return this.toEpochDay() > other.toEpochDay(); } /** * Checks if this date is before the specified date ignoring the chronology. * <p> * This method differs from the comparison in {@link #compareTo} in that it * only compares the underlying date and not the chronology. * This allows dates in different calendar systems to be compared based * on the time-line position. * This is equivalent to using {@code date1.toEpochDay() < date2.toEpochDay()}. * <p> * This default implementation performs the comparison based on the epoch-day. * * @param other the other date to compare to, not null * @return true if this is before the specified date */ default boolean isBefore(ChronoLocalDate other) { return this.toEpochDay() < other.toEpochDay(); } /** * Checks if this date is equal to the specified date ignoring the chronology. * <p> * This method differs from the comparison in {@link #compareTo} in that it * only compares the underlying date and not the chronology. * This allows dates in different calendar systems to be compared based * on the time-line position. * This is equivalent to using {@code date1.toEpochDay() == date2.toEpochDay()}. * <p> * This default implementation performs the comparison based on the epoch-day. * * @param other the other date to compare to, not null * @return true if the underlying date is equal to the specified date */ default boolean isEqual(ChronoLocalDate other) { return this.toEpochDay() == other.toEpochDay(); } //----------------------------------------------------------------------- /** * Checks if this date is equal to another date, including the chronology. * <p> * Compares this date with another ensuring that the date and chronology are the same. * <p> * To compare the dates of two {@code TemporalAccessor} instances, including dates * in two different chronologies, use {@link ChronoField#EPOCH_DAY} as a comparator. * * @param obj the object to check, null returns false * @return true if this is equal to the other date */ @Override boolean equals(Object obj); /** * A hash code for this date. * * @return a suitable hash code */ @Override int hashCode(); //----------------------------------------------------------------------- /** * Outputs this date as a {@code String}. * <p> * The output will include the full local date. * * @return the formatted date, not null */ @Override String toString(); }
apache/hop
36,340
plugins/transforms/mongodb/src/main/java/org/apache/hop/pipeline/transforms/mongodbdelete/MongoDbDeleteDialog.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hop.pipeline.transforms.mongodbdelete; import com.mongodb.DBObject; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.hop.core.Const; import org.apache.hop.core.Props; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.exception.HopTransformException; import org.apache.hop.core.row.IRowMeta; import org.apache.hop.core.row.IValueMeta; import org.apache.hop.core.row.RowMeta; import org.apache.hop.core.row.value.ValueMetaFactory; import org.apache.hop.core.util.StringUtil; import org.apache.hop.core.util.Utils; import org.apache.hop.core.variables.IVariables; import org.apache.hop.core.variables.Variables; import org.apache.hop.i18n.BaseMessages; import org.apache.hop.mongo.metadata.MongoDbConnection; import org.apache.hop.mongo.wrapper.MongoClientWrapper; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.transform.TransformMeta; import org.apache.hop.ui.core.ConstUi; import org.apache.hop.ui.core.PropsUi; import org.apache.hop.ui.core.dialog.BaseDialog; import org.apache.hop.ui.core.dialog.ErrorDialog; import org.apache.hop.ui.core.dialog.ShowMessageDialog; import org.apache.hop.ui.core.gui.GuiResource; import org.apache.hop.ui.core.widget.ColumnInfo; import org.apache.hop.ui.core.widget.MetaSelectionLine; import org.apache.hop.ui.core.widget.StyledTextComp; import org.apache.hop.ui.core.widget.TableView; import org.apache.hop.ui.core.widget.TextVar; import org.apache.hop.ui.pipeline.transform.BaseTransformDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; /** Dialog class for MongoDbDelete step */ public class MongoDbDeleteDialog extends BaseTransformDialog { private static final Class<?> PKG = MongoDbDeleteDialog.class; public static final String CONST_ERROR = "Error"; public static final String CONST_MONGO_DB_INPUT_DIALOG_ERROR_MESSAGE_UNABLE_TO_CONNECT = "MongoDbInputDialog.ErrorMessage.UnableToConnect"; private MetaSelectionLine<MongoDbConnection> wConnection; protected MongoDbDeleteMeta currentMeta; protected MongoDbDeleteMeta originalMeta; private Button wbGetFields; private Button wbPreviewDocStruct; private CCombo wCollection; private TextVar wtvTimeout; private TextVar wtvWriteRetries; private TextVar wtvWriteRetryDelay; private TableView wtvMongoFieldsView; private StyledTextComp wstJsonQueryView; private Button wbUseJsonQuery; private Label wlExecuteForEachRow; private Button wcbEcuteForEachRow; private ColumnInfo[] colInf; private final List<String> inputFields = new ArrayList<>(); public MongoDbDeleteDialog( Shell parent, IVariables variables, MongoDbDeleteMeta transformMeta, PipelineMeta pipelineMeta) { super(parent, variables, transformMeta, pipelineMeta); currentMeta = transformMeta; originalMeta = (MongoDbDeleteMeta) currentMeta.clone(); } @Override public String open() { Shell parent = getParent(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); PropsUi.setLook(shell); setShellImage(shell, currentMeta); // used to listen to a text field (wTransformName) ModifyListener lsMod = e -> currentMeta.setChanged(); changed = currentMeta.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = PropsUi.getFormMargin(); formLayout.marginHeight = PropsUi.getFormMargin(); shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "MongoDbDeleteDialog.Shell.Title")); int middle = props.getMiddlePct(); int margin = PropsUi.getMargin(); // TransformName line /** various UI bits and pieces for the dialog */ Label wlTransformName = new Label(shell, SWT.RIGHT); wlTransformName.setText(BaseMessages.getString(PKG, "MongoDbDeleteDialog.TransformName.Label")); PropsUi.setLook(wlTransformName); FormData fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(middle, -margin); fd.top = new FormAttachment(0, margin); wlTransformName.setLayoutData(fd); wTransformName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wTransformName.setText(transformName); PropsUi.setLook(wTransformName); wTransformName.addModifyListener(lsMod); Control lastControl = wTransformName; // format the text field fd = new FormData(); fd.left = new FormAttachment(middle, 0); fd.top = new FormAttachment(0, margin); fd.right = new FormAttachment(100, 0); wTransformName.setLayoutData(fd); // The tabs of the dialog CTabFolder wTabFolder = new CTabFolder(shell, SWT.BORDER); PropsUi.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); // --- start of the options tab CTabItem wDeleteOptionsTab = new CTabItem(wTabFolder, SWT.NONE); wDeleteOptionsTab.setFont(GuiResource.getInstance().getFontDefault()); wDeleteOptionsTab.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.DeleteTab.TabTitle")); Composite wOutputComp = new Composite(wTabFolder, SWT.NONE); PropsUi.setLook(wOutputComp); FormLayout outputLayout = new FormLayout(); outputLayout.marginWidth = 3; outputLayout.marginHeight = 3; wOutputComp.setLayout(outputLayout); // The connection to use... // wConnection = new MetaSelectionLine<>( variables, metadataProvider, MongoDbConnection.class, wOutputComp, SWT.NONE, BaseMessages.getString(PKG, "MongoDbDeleteDialog.ConnectionName.Label"), BaseMessages.getString(PKG, "MongoDbDeleteDialog.ConnectionName.Tooltip")); FormData fdConnection = new FormData(); fdConnection.left = new FormAttachment(0, 0); fdConnection.right = new FormAttachment(100, 0); fdConnection.top = new FormAttachment(0, 0); wConnection.setLayoutData(fdConnection); lastControl = wConnection; try { wConnection.fillItems(); } catch (HopException e) { new ErrorDialog(shell, CONST_ERROR, "Error loading list of MongoDB connection names", e); } // collection line Label wlCollection = new Label(wOutputComp, SWT.RIGHT); wlCollection.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.Collection.Label")); // $NON-NLS-1$ wlCollection.setToolTipText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.Collection.TipText")); // $NON-NLS-1$ PropsUi.setLook(wlCollection); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(lastControl, margin); fd.right = new FormAttachment(middle, -margin); wlCollection.setLayoutData(fd); Button wbGetCollections = new Button(wOutputComp, SWT.PUSH | SWT.CENTER); PropsUi.setLook(wbGetCollections); wbGetCollections.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.GetCollections.Button")); // $NON-NLS-1$ fd = new FormData(); fd.right = new FormAttachment(100, 0); fd.top = new FormAttachment(lastControl, 0); wbGetCollections.setLayoutData(fd); wbGetCollections.addListener(SWT.Selection, e -> getCollectionNames()); wCollection = new CCombo(wOutputComp, SWT.BORDER); PropsUi.setLook(wCollection); wCollection.addListener( SWT.Modify, e -> { currentMeta.setChanged(); wCollection.setToolTipText(variables.resolve(wCollection.getText())); }); fd = new FormData(); fd.left = new FormAttachment(middle, 0); fd.top = new FormAttachment(lastControl, margin); fd.right = new FormAttachment(wbGetCollections, -margin); wCollection.setLayoutData(fd); // retries stuff Label retriesLab = new Label(wOutputComp, SWT.RIGHT); PropsUi.setLook(retriesLab); retriesLab.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.WriteRetries.Label")); // $NON-NLS-1$ retriesLab.setToolTipText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.WriteRetries.TipText")); // $NON-NLS-1$ fd = new FormData(); fd.left = new FormAttachment(0, -margin); fd.top = new FormAttachment(wCollection, margin); fd.right = new FormAttachment(middle, -margin); retriesLab.setLayoutData(fd); wtvWriteRetries = new TextVar(variables, wOutputComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); PropsUi.setLook(wtvWriteRetries); fd = new FormData(); fd.left = new FormAttachment(middle, 0); fd.top = new FormAttachment(wCollection, margin); fd.right = new FormAttachment(100, 0); wtvWriteRetries.setLayoutData(fd); wtvWriteRetries.addModifyListener( e -> wtvWriteRetries.setToolTipText(variables.resolve(wtvWriteRetries.getText()))); Label retriesDelayLab = new Label(wOutputComp, SWT.RIGHT); PropsUi.setLook(retriesDelayLab); retriesDelayLab.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.WriteRetriesDelay.Label")); // $NON-NLS-1$ fd = new FormData(); fd.left = new FormAttachment(0, -margin); fd.top = new FormAttachment(wtvWriteRetries, margin); fd.right = new FormAttachment(middle, -margin); retriesDelayLab.setLayoutData(fd); wtvWriteRetryDelay = new TextVar(variables, wOutputComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); PropsUi.setLook(wtvWriteRetryDelay); fd = new FormData(); fd.left = new FormAttachment(middle, 0); fd.top = new FormAttachment(wtvWriteRetries, margin); fd.right = new FormAttachment(100, 0); wtvWriteRetryDelay.setLayoutData(fd); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wOutputComp.setLayoutData(fd); wOutputComp.layout(); wDeleteOptionsTab.setControl(wOutputComp); // --- start of the fields tab CTabItem mWQueryTab = new CTabItem(wTabFolder, SWT.NONE); mWQueryTab.setFont(GuiResource.getInstance().getFontDefault()); mWQueryTab.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.QueryTab.TabTitle")); // $NON-NLS-1$ Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE); PropsUi.setLook(wFieldsComp); FormLayout filterLayout = new FormLayout(); filterLayout.marginWidth = 3; filterLayout.marginHeight = 3; wFieldsComp.setLayout(filterLayout); // use query Label useDefinedQueryLab = new Label(wFieldsComp, SWT.RIGHT); useDefinedQueryLab.setText(BaseMessages.getString(PKG, "MongoDbDeleteDialog.useQuery.Label")); useDefinedQueryLab.setToolTipText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.useQuery.TipText")); PropsUi.setLook(useDefinedQueryLab); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, margin); fd.right = new FormAttachment(middle, -margin); useDefinedQueryLab.setLayoutData(fd); wbUseJsonQuery = new Button(wFieldsComp, SWT.CHECK); PropsUi.setLook(wbUseJsonQuery); wbUseJsonQuery.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { currentMeta.setChanged(); if (wbUseJsonQuery.getSelection()) { // show query setQueryJsonVisibility(true); // hide m_mongoFields setQueryFieldVisiblity(false); } else { // show m_mongoFieldsView setQueryFieldVisiblity(true); // hide query setQueryJsonVisibility(false); } } }); fd = new FormData(); fd.right = new FormAttachment(100, -margin); fd.top = new FormAttachment(0, margin * 3); fd.left = new FormAttachment(middle, 0); wbUseJsonQuery.setLayoutData(fd); colInf = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString(PKG, "MongoDbDeleteDialog.Fields.Path"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbDeleteDialog.Fields.Comparator"), ColumnInfo.COLUMN_TYPE_CCOMBO, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbDeleteDialog.Fields.Incoming1"), ColumnInfo.COLUMN_TYPE_CCOMBO, false), new ColumnInfo( BaseMessages.getString(PKG, "MongoDbDeleteDialog.Fields.Incoming2"), ColumnInfo.COLUMN_TYPE_CCOMBO, false) }; colInf[1].setComboValues(Comparator.asLabel()); colInf[1].setReadOnly(true); // Search the fields in the background final Runnable runnable = new Runnable() { public void run() { TransformMeta stepMeta = pipelineMeta.findTransform(transformName); if (stepMeta != null) { try { IRowMeta row = pipelineMeta.getPrevTransformFields(variables, stepMeta); // Remember these fields... for (int i = 0; i < row.size(); i++) { inputFields.add(row.getValueMeta(i).getName()); } setComboBoxes(); } catch (HopTransformException e) { log.logError( toString(), BaseMessages.getString(PKG, "MongoDbDeleteDialog.Log.UnableToFindInput")); } } } }; new Thread(runnable).start(); // get fields but wbGetFields = new Button(wFieldsComp, SWT.PUSH | SWT.CENTER); PropsUi.setLook(wbGetFields); wbGetFields.setText(BaseMessages.getString(PKG, "MongoDbDeleteDialog.GetFieldsBut")); fd = new FormData(); fd.bottom = new FormAttachment(100, -margin * 2); fd.left = new FormAttachment(0, margin); wbGetFields.setLayoutData(fd); wbGetFields.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { getFields(); } }); wbPreviewDocStruct = new Button(wFieldsComp, SWT.PUSH | SWT.CENTER); PropsUi.setLook(wbPreviewDocStruct); wbPreviewDocStruct.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.PreviewDocStructBut")); fd = new FormData(); fd.bottom = new FormAttachment(100, -margin * 2); fd.left = new FormAttachment(wbGetFields, margin); wbPreviewDocStruct.setLayoutData(fd); wbPreviewDocStruct.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { previewDocStruct(); } }); wtvMongoFieldsView = new TableView( variables, wFieldsComp, SWT.FULL_SELECTION | SWT.MULTI, colInf, 1, lsMod, props); fd = new FormData(); fd.top = new FormAttachment(wbUseJsonQuery, margin * 2); fd.bottom = new FormAttachment(wbGetFields, -margin * 2); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); wtvMongoFieldsView.setLayoutData(fd); // JSON Query wlExecuteForEachRow = new Label(wFieldsComp, SWT.RIGHT); wlExecuteForEachRow.setText( BaseMessages.getString(PKG, "MongoDbDeleteDialog.execEachRow.Label")); PropsUi.setLook(wlExecuteForEachRow); fd = new FormData(); fd.bottom = new FormAttachment(100, -margin * 2); fd.left = new FormAttachment(0, margin); wlExecuteForEachRow.setLayoutData(fd); wcbEcuteForEachRow = new Button(wFieldsComp, SWT.CHECK); PropsUi.setLook(wcbEcuteForEachRow); wcbEcuteForEachRow.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { currentMeta.setChanged(); } }); fd = new FormData(); fd.bottom = new FormAttachment(100, -margin * 2); fd.left = new FormAttachment(wlExecuteForEachRow, margin); wcbEcuteForEachRow.setLayoutData(fd); wstJsonQueryView = new StyledTextComp( variables, wFieldsComp, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); PropsUi.setLook(wstJsonQueryView, Props.WIDGET_STYLE_FIXED); wstJsonQueryView.addModifyListener(lsMod); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.right = new FormAttachment(100, -margin * 3); fd.top = new FormAttachment(wbUseJsonQuery, margin * 2); fd.bottom = new FormAttachment(wlExecuteForEachRow, -margin * 2); wstJsonQueryView.setLayoutData(fd); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(0, 0); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, 0); wFieldsComp.setLayoutData(fd); wFieldsComp.layout(); mWQueryTab.setControl(wFieldsComp); fd = new FormData(); fd.left = new FormAttachment(0, 0); fd.top = new FormAttachment(wTransformName, margin); fd.right = new FormAttachment(100, 0); fd.bottom = new FormAttachment(100, -50); wTabFolder.setLayoutData(fd); // Buttons inherited from BaseStepDialog wOk = new Button(shell, SWT.PUSH); wOk.setText(BaseMessages.getString(PKG, "System.Button.OK")); // $NON-NLS-1$ wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); // $NON-NLS-1$ setButtonPositions(new Button[] {wOk, wCancel}, margin, wTabFolder); // Add listeners wCancel.addListener(SWT.Selection, e -> cancel()); wOk.addListener(SWT.Selection, e -> ok()); wTransformName.addListener(SWT.Selection, e -> ok()); wTabFolder.setSelection(0); setSize(); getData(); // hide if not use json query if (currentMeta.isUseJsonQuery()) { setQueryFieldVisiblity(false); } else { setQueryJsonVisibility(false); } BaseDialog.defaultShellHandling(shell, c -> ok(), c -> cancel()); return transformName; } protected void cancel() { transformName = null; currentMeta.setChanged(changed); dispose(); } private void ok() { if (StringUtil.isEmpty(wTransformName.getText())) { return; } transformName = wTransformName.getText(); getInfo(currentMeta); if ((!currentMeta.isUseJsonQuery()) && (Utils.isEmpty(currentMeta.getMongoFields()))) { // popup dialog warning that no paths have been defined showNoFieldMessageDialog(); } else if (currentMeta.isUseJsonQuery() && StringUtil.isEmpty(currentMeta.getJsonQuery())) { showNoQueryWarningDialog(); } if (!originalMeta.equals(currentMeta)) { currentMeta.setChanged(); changed = currentMeta.hasChanged(); } dispose(); } private void setupCustomWriteConcernNames() { try { String connectionName = variables.resolve(wConnection.getText()); MongoDbConnection connection = metadataProvider.getSerializer(MongoDbConnection.class).load(connectionName); if (!StringUtil.isEmpty(connectionName)) { MongoDbDeleteMeta meta = new MongoDbDeleteMeta(); getInfo(meta); try { MongoClientWrapper wrapper = connection.createWrapper(variables, log); List<String> custom = new ArrayList<>(); try { custom = wrapper.getLastErrorModes(); } finally { wrapper.dispose(); } } catch (Exception e) { logError( BaseMessages.getString(PKG, "MongoDbDeleteDialog.ErrorMessage.UnableToConnect"), e); new ErrorDialog( shell, BaseMessages.getString(PKG, "MongoDbDeleteDialog.ErrorMessage." + "UnableToConnect"), BaseMessages.getString(PKG, "MongoDbDeleteDialog.ErrorMessage.UnableToConnect"), e); } } else { ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, BaseMessages.getString( PKG, "MongoDbDeleteDialog.ErrorMessage.MissingConnectionDetails.Title"), BaseMessages.getString( PKG, "MongoDbDeleteDialog.ErrorMessage.MissingConnectionDetails", "host name(s)")); smd.open(); } } catch (Exception e) { new ErrorDialog(shell, CONST_ERROR, "Error getting collections", e); } } private void getFields() { try { IRowMeta r = pipelineMeta.getPrevTransformFields(variables, transformName); if (r != null) { BaseTransformDialog.getFieldsFromPrevious( r, wtvMongoFieldsView, 1, new int[] {1, 3}, null, -1, -1, null); } } catch (HopTransformException e) { logError(BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"), e); new ErrorDialog( shell, BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Title"), BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"), e); } } private void getInfo(MongoDbDeleteMeta meta) { meta.setConnectionName(wConnection.getText()); meta.setCollection(wCollection.getText()); meta.setWriteRetries(wtvWriteRetries.getText()); meta.setWriteRetryDelay(wtvWriteRetryDelay.getText()); meta.setUseJsonQuery(wbUseJsonQuery.getSelection()); meta.setExecuteForEachIncomingRow(wcbEcuteForEachRow.getSelection()); meta.setJsonQuery(wstJsonQueryView.getText()); meta.setMongoFields(tableToMongoFieldList()); } private List<MongoDbDeleteField> tableToMongoFieldList() { int numNonEmpty = wtvMongoFieldsView.nrNonEmpty(); if (numNonEmpty > 0) { List<MongoDbDeleteField> mongoFields = new ArrayList<>(); for (int i = 0; i < numNonEmpty; i++) { TableItem item = wtvMongoFieldsView.getNonEmpty(i); String path = item.getText(1).trim(); String comparator = item.getText(2).trim(); String field1 = item.getText(3).trim(); String field2 = item.getText(4).trim(); MongoDbDeleteField newField = new MongoDbDeleteField(); newField.mongoDocPath = path; if (StringUtil.isEmpty(comparator)) { comparator = Comparator.EQUAL.getValue(); } newField.comparator = comparator; newField.incomingField1 = field1; newField.incomingField2 = field2; mongoFields.add(newField); } return mongoFields; } return null; } private void getData() { wConnection.setText(Const.NVL(currentMeta.getConnectionName(), "")); wCollection.setText(Const.NVL(currentMeta.getCollection(), "")); // $NON-NLS-1$ wtvWriteRetries.setText( Const.NVL( currentMeta.getWriteRetries(), "" //$NON-NLS-1$ + currentMeta.nbRetries)); wtvWriteRetryDelay.setText( Const.NVL( currentMeta.getWriteRetryDelay(), "" //$NON-NLS-1$ + currentMeta.nbRetries)); wbUseJsonQuery.setSelection(currentMeta.isUseJsonQuery()); wcbEcuteForEachRow.setSelection(currentMeta.isExecuteForEachIncomingRow()); wstJsonQueryView.setText(Const.NVL(currentMeta.getJsonQuery(), "")); List<MongoDbDeleteField> mongoFields = currentMeta.getMongoFields(); if (!Utils.isEmpty(mongoFields)) { for (MongoDbDeleteField field : mongoFields) { TableItem item = new TableItem(wtvMongoFieldsView.table, SWT.NONE); item.setText(1, Const.NVL(field.mongoDocPath, "")); item.setText(2, Const.NVL(field.comparator, "")); item.setText(3, Const.NVL(field.incomingField1, "")); item.setText(4, Const.NVL(field.incomingField2, "")); } wtvMongoFieldsView.removeEmptyRows(); wtvMongoFieldsView.setRowNums(); wtvMongoFieldsView.optWidth(true); } } protected void setComboBoxes() { String[] fieldNames = ConstUi.sortFieldNames(inputFields); colInf[2].setComboValues(fieldNames); colInf[2].setReadOnly(false); colInf[3].setComboValues(fieldNames); colInf[3].setReadOnly(false); } private void getCollectionNames() { try { String connectionName = variables.resolve(wConnection.getText()); String current = wCollection.getText(); wCollection.removeAll(); MongoDbConnection connection = metadataProvider.getSerializer(MongoDbConnection.class).load(connectionName); String databaseName = variables.resolve(connection.getDbName()); if (!StringUtils.isEmpty(connectionName)) { final MongoDbDeleteMeta meta = new MongoDbDeleteMeta(); getInfo(meta); try { MongoClientWrapper wrapper = connection.createWrapper(variables, log); Set<String> collections; try { collections = wrapper.getCollectionsNames(databaseName); } finally { wrapper.dispose(); } for (String c : collections) { wCollection.add(c); } } catch (Exception e) { logError( BaseMessages.getString( PKG, CONST_MONGO_DB_INPUT_DIALOG_ERROR_MESSAGE_UNABLE_TO_CONNECT), e); new ErrorDialog( shell, BaseMessages.getString( PKG, CONST_MONGO_DB_INPUT_DIALOG_ERROR_MESSAGE_UNABLE_TO_CONNECT), BaseMessages.getString( PKG, CONST_MONGO_DB_INPUT_DIALOG_ERROR_MESSAGE_UNABLE_TO_CONNECT), e); } } else { // popup some feedback String missingConnDetails = ""; if (StringUtils.isEmpty(connectionName)) { missingConnDetails += "connection name"; } ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK, BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails.Title"), BaseMessages.getString( PKG, "MongoDbInputDialog.ErrorMessage.MissingConnectionDetails", missingConnDetails)); smd.open(); } if (!StringUtils.isEmpty(current)) { wCollection.setText(current); } } catch (Exception e) { new ErrorDialog(shell, CONST_ERROR, "Error getting collections", e); } } private void previewDocStruct() { List<MongoDbDeleteField> mongoFields = tableToMongoFieldList(); if (Utils.isEmpty(mongoFields)) { // popup dialog warning that no paths have been defined showNoFieldMessageDialog(); return; } // Try and get meta data on incoming fields IRowMeta actualR = null; IRowMeta r; boolean gotGenuineRowMeta = false; try { actualR = pipelineMeta.getPrevTransformFields(variables, transformName); gotGenuineRowMeta = true; } catch (HopTransformException e) { // don't complain if we can't } r = new RowMeta(); Object[] dummyRow = new Object [mongoFields.size() * 2]; // multiply by 2, because possiblity use between that required 2 value int i = 0; try { for (MongoDbDeleteField field : mongoFields) { // set up dummy row meta if (!StringUtil.isEmpty(field.incomingField1) && !StringUtil.isEmpty(field.incomingField2)) { IValueMeta vm1 = ValueMetaFactory.createValueMeta(IValueMeta.TYPE_STRING); vm1.setName(field.incomingField1); r.addValueMeta(vm1); IValueMeta vm2 = ValueMetaFactory.createValueMeta(IValueMeta.TYPE_STRING); vm2.setName(field.incomingField2); r.addValueMeta(vm2); String val1 = getValueToDisplay(gotGenuineRowMeta, actualR, field.incomingField1); dummyRow[i++] = val1; String val2 = getValueToDisplay(gotGenuineRowMeta, actualR, field.incomingField2); dummyRow[i++] = val2; } else { IValueMeta vm = ValueMetaFactory.createValueMeta(IValueMeta.TYPE_STRING); vm.setName(field.incomingField1); r.addValueMeta(vm); String val = getValueToDisplay(gotGenuineRowMeta, actualR, field.incomingField1); dummyRow[i++] = val; } } IVariables vs = new Variables(); for (MongoDbDeleteField m : mongoFields) { m.init(vs); } String toDisplay = ""; String windowTitle = BaseMessages.getString(PKG, "MongoDbDeleteDialog.PreviewDocStructure.Title"); DBObject query = MongoDbDeleteData.getQueryObject(mongoFields, r, dummyRow, vs); toDisplay = BaseMessages.getString(PKG, "MongoDbDeleteDialog.PreviewModifierUpdate.Heading1") + ": \n\n" + prettyPrintDocStructure(query.toString()); ShowMessageDialog smd = new ShowMessageDialog(shell, SWT.ICON_INFORMATION | SWT.OK, windowTitle, toDisplay, true); smd.open(); } catch (Exception ex) { logError( BaseMessages.getString( PKG, "MongoDbDeleteDialog.ErrorMessage.ProblemPreviewingDocStructure.Message") + ":\n\n" + ex.getMessage(), ex); new ErrorDialog( shell, BaseMessages.getString( PKG, "MongoDbDeleteDialog.ErrorMessage.ProblemPreviewingDocStructure.Title"), BaseMessages.getString( PKG, "MongoDbDeleteDialog.ErrorMessage.ProblemPreviewingDocStructure.Message") + ":\n\n" + ex.getMessage(), ex); return; } } private String getValueToDisplay(boolean genuineRowMeta, IRowMeta rmi, String fieldName) { String val = ""; if (genuineRowMeta && rmi.indexOfValue(fieldName) >= 0) { int index = rmi.indexOfValue(fieldName); switch (rmi.getValueMeta(index).getType()) { case IValueMeta.TYPE_STRING: val = "<string val>"; break; case IValueMeta.TYPE_INTEGER: val = "<integer val>"; break; case IValueMeta.TYPE_NUMBER: val = "<number val>"; break; case IValueMeta.TYPE_BOOLEAN: val = "<bool val>"; break; case IValueMeta.TYPE_DATE: val = "<date val>"; break; case IValueMeta.TYPE_BINARY: val = "<binary val>"; break; default: try { int uuidTypeId = ValueMetaFactory.getIdForValueMeta("UUID"); if (rmi.getValueMeta(index).getType() == uuidTypeId) { val = "<UUID val>"; } else { val = "<unsupported value type>"; } } catch (Exception ignore) { // UUID plugin not present, fall through } } } else { val = "<value>"; } return val; } private static enum Element { OPEN_BRACE, CLOSE_BRACE, OPEN_BRACKET, CLOSE_BRACKET, COMMA } private static void pad(StringBuffer toPad, int numBlanks) { for (int i = 0; i < numBlanks; i++) { toPad.append(' '); } } public static String prettyPrintDocStructure(String toFormat) { StringBuffer result = new StringBuffer(); int indent = 0; String source = toFormat.replaceAll("[ ]*,", ","); // $NON-NLS-1$ //$NON-NLS-2$ Element next = Element.OPEN_BRACE; while (!source.isEmpty()) { source = source.trim(); String toIndent = ""; // $NON-NLS-1$ int minIndex = Integer.MAX_VALUE; char targetChar = '{'; if (source.indexOf('{') > -1 && source.indexOf('{') < minIndex) { next = Element.OPEN_BRACE; minIndex = source.indexOf('{'); targetChar = '{'; } if (source.indexOf('}') > -1 && source.indexOf('}') < minIndex) { next = Element.CLOSE_BRACE; minIndex = source.indexOf('}'); targetChar = '}'; } if (source.indexOf('[') > -1 && source.indexOf('[') < minIndex) { next = Element.OPEN_BRACKET; minIndex = source.indexOf('['); targetChar = '['; } if (source.indexOf(']') > -1 && source.indexOf(']') < minIndex) { next = Element.CLOSE_BRACKET; minIndex = source.indexOf(']'); targetChar = ']'; } if (source.indexOf(',') > -1 && source.indexOf(',') < minIndex) { next = Element.COMMA; minIndex = source.indexOf(','); targetChar = ','; } if (minIndex == 0) { if (next == Element.CLOSE_BRACE || next == Element.CLOSE_BRACKET) { indent -= 2; } pad(result, indent); String comma = ""; // $NON-NLS-1$ int offset = 1; if (source.length() >= 2 && source.charAt(1) == ',') { comma = ","; // $NON-NLS-1$ offset = 2; } result.append(targetChar).append(comma).append("\n"); // $NON-NLS-1$ source = source.substring(offset); } else { pad(result, indent); if (next == Element.CLOSE_BRACE || next == Element.CLOSE_BRACKET) { toIndent = source.substring(0, minIndex); source = source.substring(minIndex); } else { toIndent = source.substring(0, minIndex + 1); source = source.substring(minIndex + 1); } result.append(toIndent.trim()).append("\n"); // $NON-NLS-1$ } if (next == Element.OPEN_BRACE || next == Element.OPEN_BRACKET) { indent += 2; } } return result.toString(); } private void showNoFieldMessageDialog() { ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK | SWT.CENTER, BaseMessages.getString( PKG, "MongoDbDeleteDialog.ErrorMessage.NoFieldPathsDefined.Title"), BaseMessages.getString(PKG, "MongoDbDeleteDialog.ErrorMessage.NoFieldPathsDefined")); smd.open(); } private void showNoQueryWarningDialog() { ShowMessageDialog smd = new ShowMessageDialog( shell, SWT.ICON_WARNING | SWT.OK | SWT.CENTER, BaseMessages.getString( PKG, "MongoDbDeleteDialog.ErrorMessage.NoJsonQueryDefined.Title"), BaseMessages.getString(PKG, "MongoDbDeleteDialog.ErrorMessage.NoJsonQueryDefined")); smd.open(); } private void setQueryFieldVisiblity(boolean visible) { wtvMongoFieldsView.setVisible(visible); wbGetFields.setVisible(visible); wbPreviewDocStruct.setVisible(visible); } private void setQueryJsonVisibility(boolean visible) { wstJsonQueryView.setVisible(visible); wlExecuteForEachRow.setVisible(visible); wcbEcuteForEachRow.setVisible(visible); } }
googleapis/google-cloud-java
36,398
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/EvaluateDatasetResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/evaluation_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Response in LRO for EvaluationService.EvaluateDataset. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse} */ public final class EvaluateDatasetResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse) EvaluateDatasetResponseOrBuilder { private static final long serialVersionUID = 0L; // Use EvaluateDatasetResponse.newBuilder() to construct. private EvaluateDatasetResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private EvaluateDatasetResponse() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new EvaluateDatasetResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_EvaluateDatasetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_EvaluateDatasetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse.class, com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse.Builder.class); } private int bitField0_; public static final int AGGREGATION_OUTPUT_FIELD_NUMBER = 1; private com.google.cloud.aiplatform.v1beta1.AggregationOutput aggregationOutput_; /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the aggregationOutput field is set. */ @java.lang.Override public boolean hasAggregationOutput() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The aggregationOutput. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.AggregationOutput getAggregationOutput() { return aggregationOutput_ == null ? com.google.cloud.aiplatform.v1beta1.AggregationOutput.getDefaultInstance() : aggregationOutput_; } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.AggregationOutputOrBuilder getAggregationOutputOrBuilder() { return aggregationOutput_ == null ? com.google.cloud.aiplatform.v1beta1.AggregationOutput.getDefaultInstance() : aggregationOutput_; } public static final int OUTPUT_INFO_FIELD_NUMBER = 3; private com.google.cloud.aiplatform.v1beta1.OutputInfo outputInfo_; /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the outputInfo field is set. */ @java.lang.Override public boolean hasOutputInfo() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The outputInfo. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.OutputInfo getOutputInfo() { return outputInfo_ == null ? com.google.cloud.aiplatform.v1beta1.OutputInfo.getDefaultInstance() : outputInfo_; } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.OutputInfoOrBuilder getOutputInfoOrBuilder() { return outputInfo_ == null ? com.google.cloud.aiplatform.v1beta1.OutputInfo.getDefaultInstance() : outputInfo_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getAggregationOutput()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getOutputInfo()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getAggregationOutput()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getOutputInfo()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse other = (com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse) obj; if (hasAggregationOutput() != other.hasAggregationOutput()) return false; if (hasAggregationOutput()) { if (!getAggregationOutput().equals(other.getAggregationOutput())) return false; } if (hasOutputInfo() != other.hasOutputInfo()) return false; if (hasOutputInfo()) { if (!getOutputInfo().equals(other.getOutputInfo())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasAggregationOutput()) { hash = (37 * hash) + AGGREGATION_OUTPUT_FIELD_NUMBER; hash = (53 * hash) + getAggregationOutput().hashCode(); } if (hasOutputInfo()) { hash = (37 * hash) + OUTPUT_INFO_FIELD_NUMBER; hash = (53 * hash) + getOutputInfo().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response in LRO for EvaluationService.EvaluateDataset. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse) com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_EvaluateDatasetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_EvaluateDatasetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse.class, com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getAggregationOutputFieldBuilder(); getOutputInfoFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; aggregationOutput_ = null; if (aggregationOutputBuilder_ != null) { aggregationOutputBuilder_.dispose(); aggregationOutputBuilder_ = null; } outputInfo_ = null; if (outputInfoBuilder_ != null) { outputInfoBuilder_.dispose(); outputInfoBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_EvaluateDatasetResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse build() { com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse buildPartial() { com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse result = new com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.aggregationOutput_ = aggregationOutputBuilder_ == null ? aggregationOutput_ : aggregationOutputBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.outputInfo_ = outputInfoBuilder_ == null ? outputInfo_ : outputInfoBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse other) { if (other == com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse.getDefaultInstance()) return this; if (other.hasAggregationOutput()) { mergeAggregationOutput(other.getAggregationOutput()); } if (other.hasOutputInfo()) { mergeOutputInfo(other.getOutputInfo()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage( getAggregationOutputFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 26: { input.readMessage(getOutputInfoFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.aiplatform.v1beta1.AggregationOutput aggregationOutput_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.AggregationOutput, com.google.cloud.aiplatform.v1beta1.AggregationOutput.Builder, com.google.cloud.aiplatform.v1beta1.AggregationOutputOrBuilder> aggregationOutputBuilder_; /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the aggregationOutput field is set. */ public boolean hasAggregationOutput() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The aggregationOutput. */ public com.google.cloud.aiplatform.v1beta1.AggregationOutput getAggregationOutput() { if (aggregationOutputBuilder_ == null) { return aggregationOutput_ == null ? com.google.cloud.aiplatform.v1beta1.AggregationOutput.getDefaultInstance() : aggregationOutput_; } else { return aggregationOutputBuilder_.getMessage(); } } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setAggregationOutput( com.google.cloud.aiplatform.v1beta1.AggregationOutput value) { if (aggregationOutputBuilder_ == null) { if (value == null) { throw new NullPointerException(); } aggregationOutput_ = value; } else { aggregationOutputBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setAggregationOutput( com.google.cloud.aiplatform.v1beta1.AggregationOutput.Builder builderForValue) { if (aggregationOutputBuilder_ == null) { aggregationOutput_ = builderForValue.build(); } else { aggregationOutputBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeAggregationOutput( com.google.cloud.aiplatform.v1beta1.AggregationOutput value) { if (aggregationOutputBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && aggregationOutput_ != null && aggregationOutput_ != com.google.cloud.aiplatform.v1beta1.AggregationOutput.getDefaultInstance()) { getAggregationOutputBuilder().mergeFrom(value); } else { aggregationOutput_ = value; } } else { aggregationOutputBuilder_.mergeFrom(value); } if (aggregationOutput_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearAggregationOutput() { bitField0_ = (bitField0_ & ~0x00000001); aggregationOutput_ = null; if (aggregationOutputBuilder_ != null) { aggregationOutputBuilder_.dispose(); aggregationOutputBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.AggregationOutput.Builder getAggregationOutputBuilder() { bitField0_ |= 0x00000001; onChanged(); return getAggregationOutputFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.AggregationOutputOrBuilder getAggregationOutputOrBuilder() { if (aggregationOutputBuilder_ != null) { return aggregationOutputBuilder_.getMessageOrBuilder(); } else { return aggregationOutput_ == null ? com.google.cloud.aiplatform.v1beta1.AggregationOutput.getDefaultInstance() : aggregationOutput_; } } /** * * * <pre> * Output only. Aggregation statistics derived from results of * EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.AggregationOutput aggregation_output = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.AggregationOutput, com.google.cloud.aiplatform.v1beta1.AggregationOutput.Builder, com.google.cloud.aiplatform.v1beta1.AggregationOutputOrBuilder> getAggregationOutputFieldBuilder() { if (aggregationOutputBuilder_ == null) { aggregationOutputBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.AggregationOutput, com.google.cloud.aiplatform.v1beta1.AggregationOutput.Builder, com.google.cloud.aiplatform.v1beta1.AggregationOutputOrBuilder>( getAggregationOutput(), getParentForChildren(), isClean()); aggregationOutput_ = null; } return aggregationOutputBuilder_; } private com.google.cloud.aiplatform.v1beta1.OutputInfo outputInfo_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.OutputInfo, com.google.cloud.aiplatform.v1beta1.OutputInfo.Builder, com.google.cloud.aiplatform.v1beta1.OutputInfoOrBuilder> outputInfoBuilder_; /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the outputInfo field is set. */ public boolean hasOutputInfo() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The outputInfo. */ public com.google.cloud.aiplatform.v1beta1.OutputInfo getOutputInfo() { if (outputInfoBuilder_ == null) { return outputInfo_ == null ? com.google.cloud.aiplatform.v1beta1.OutputInfo.getDefaultInstance() : outputInfo_; } else { return outputInfoBuilder_.getMessage(); } } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setOutputInfo(com.google.cloud.aiplatform.v1beta1.OutputInfo value) { if (outputInfoBuilder_ == null) { if (value == null) { throw new NullPointerException(); } outputInfo_ = value; } else { outputInfoBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setOutputInfo( com.google.cloud.aiplatform.v1beta1.OutputInfo.Builder builderForValue) { if (outputInfoBuilder_ == null) { outputInfo_ = builderForValue.build(); } else { outputInfoBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeOutputInfo(com.google.cloud.aiplatform.v1beta1.OutputInfo value) { if (outputInfoBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && outputInfo_ != null && outputInfo_ != com.google.cloud.aiplatform.v1beta1.OutputInfo.getDefaultInstance()) { getOutputInfoBuilder().mergeFrom(value); } else { outputInfo_ = value; } } else { outputInfoBuilder_.mergeFrom(value); } if (outputInfo_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearOutputInfo() { bitField0_ = (bitField0_ & ~0x00000002); outputInfo_ = null; if (outputInfoBuilder_ != null) { outputInfoBuilder_.dispose(); outputInfoBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.OutputInfo.Builder getOutputInfoBuilder() { bitField0_ |= 0x00000002; onChanged(); return getOutputInfoFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.OutputInfoOrBuilder getOutputInfoOrBuilder() { if (outputInfoBuilder_ != null) { return outputInfoBuilder_.getMessageOrBuilder(); } else { return outputInfo_ == null ? com.google.cloud.aiplatform.v1beta1.OutputInfo.getDefaultInstance() : outputInfo_; } } /** * * * <pre> * Output only. Output info for EvaluationService.EvaluateDataset. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.OutputInfo output_info = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.OutputInfo, com.google.cloud.aiplatform.v1beta1.OutputInfo.Builder, com.google.cloud.aiplatform.v1beta1.OutputInfoOrBuilder> getOutputInfoFieldBuilder() { if (outputInfoBuilder_ == null) { outputInfoBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.OutputInfo, com.google.cloud.aiplatform.v1beta1.OutputInfo.Builder, com.google.cloud.aiplatform.v1beta1.OutputInfoOrBuilder>( getOutputInfo(), getParentForChildren(), isClean()); outputInfo_ = null; } return outputInfoBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse) private static final com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse(); } public static com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<EvaluateDatasetResponse> PARSER = new com.google.protobuf.AbstractParser<EvaluateDatasetResponse>() { @java.lang.Override public EvaluateDatasetResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<EvaluateDatasetResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<EvaluateDatasetResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.EvaluateDatasetResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,483
java-speech/proto-google-cloud-speech-v1/src/main/java/com/google/cloud/speech/v1/SpeechContext.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/speech/v1/cloud_speech.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.speech.v1; /** * * * <pre> * Provides "hints" to the speech recognizer to favor specific words and phrases * in the results. * </pre> * * Protobuf type {@code google.cloud.speech.v1.SpeechContext} */ public final class SpeechContext extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v1.SpeechContext) SpeechContextOrBuilder { private static final long serialVersionUID = 0L; // Use SpeechContext.newBuilder() to construct. private SpeechContext(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SpeechContext() { phrases_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SpeechContext(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1.SpeechProto .internal_static_google_cloud_speech_v1_SpeechContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1.SpeechProto .internal_static_google_cloud_speech_v1_SpeechContext_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1.SpeechContext.class, com.google.cloud.speech.v1.SpeechContext.Builder.class); } public static final int PHRASES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList phrases_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @return A list containing the phrases. */ public com.google.protobuf.ProtocolStringList getPhrasesList() { return phrases_; } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @return The count of phrases. */ public int getPhrasesCount() { return phrases_.size(); } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param index The index of the element to return. * @return The phrases at the given index. */ public java.lang.String getPhrases(int index) { return phrases_.get(index); } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param index The index of the value to return. * @return The bytes of the phrases at the given index. */ public com.google.protobuf.ByteString getPhrasesBytes(int index) { return phrases_.getByteString(index); } public static final int BOOST_FIELD_NUMBER = 4; private float boost_ = 0F; /** * * * <pre> * Hint Boost. Positive value will increase the probability that a specific * phrase will be recognized over other similar sounding phrases. The higher * the boost, the higher the chance of false positive recognition as well. * Negative boost values would correspond to anti-biasing. Anti-biasing is not * enabled, so negative boost will simply be ignored. Though `boost` can * accept a wide range of positive values, most use cases are best served with * values between 0 and 20. We recommend using a binary search approach to * finding the optimal value for your use case. * </pre> * * <code>float boost = 4;</code> * * @return The boost. */ @java.lang.Override public float getBoost() { return boost_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < phrases_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, phrases_.getRaw(i)); } if (java.lang.Float.floatToRawIntBits(boost_) != 0) { output.writeFloat(4, boost_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; { int dataSize = 0; for (int i = 0; i < phrases_.size(); i++) { dataSize += computeStringSizeNoTag(phrases_.getRaw(i)); } size += dataSize; size += 1 * getPhrasesList().size(); } if (java.lang.Float.floatToRawIntBits(boost_) != 0) { size += com.google.protobuf.CodedOutputStream.computeFloatSize(4, boost_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.speech.v1.SpeechContext)) { return super.equals(obj); } com.google.cloud.speech.v1.SpeechContext other = (com.google.cloud.speech.v1.SpeechContext) obj; if (!getPhrasesList().equals(other.getPhrasesList())) return false; if (java.lang.Float.floatToIntBits(getBoost()) != java.lang.Float.floatToIntBits(other.getBoost())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getPhrasesCount() > 0) { hash = (37 * hash) + PHRASES_FIELD_NUMBER; hash = (53 * hash) + getPhrasesList().hashCode(); } hash = (37 * hash) + BOOST_FIELD_NUMBER; hash = (53 * hash) + java.lang.Float.floatToIntBits(getBoost()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.speech.v1.SpeechContext parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1.SpeechContext parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1.SpeechContext parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1.SpeechContext parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1.SpeechContext parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1.SpeechContext parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1.SpeechContext parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1.SpeechContext parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1.SpeechContext parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v1.SpeechContext parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1.SpeechContext parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1.SpeechContext parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.speech.v1.SpeechContext prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Provides "hints" to the speech recognizer to favor specific words and phrases * in the results. * </pre> * * Protobuf type {@code google.cloud.speech.v1.SpeechContext} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v1.SpeechContext) com.google.cloud.speech.v1.SpeechContextOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1.SpeechProto .internal_static_google_cloud_speech_v1_SpeechContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1.SpeechProto .internal_static_google_cloud_speech_v1_SpeechContext_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1.SpeechContext.class, com.google.cloud.speech.v1.SpeechContext.Builder.class); } // Construct using com.google.cloud.speech.v1.SpeechContext.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; phrases_ = com.google.protobuf.LazyStringArrayList.emptyList(); boost_ = 0F; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.speech.v1.SpeechProto .internal_static_google_cloud_speech_v1_SpeechContext_descriptor; } @java.lang.Override public com.google.cloud.speech.v1.SpeechContext getDefaultInstanceForType() { return com.google.cloud.speech.v1.SpeechContext.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v1.SpeechContext build() { com.google.cloud.speech.v1.SpeechContext result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v1.SpeechContext buildPartial() { com.google.cloud.speech.v1.SpeechContext result = new com.google.cloud.speech.v1.SpeechContext(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.speech.v1.SpeechContext result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { phrases_.makeImmutable(); result.phrases_ = phrases_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.boost_ = boost_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.speech.v1.SpeechContext) { return mergeFrom((com.google.cloud.speech.v1.SpeechContext) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v1.SpeechContext other) { if (other == com.google.cloud.speech.v1.SpeechContext.getDefaultInstance()) return this; if (!other.phrases_.isEmpty()) { if (phrases_.isEmpty()) { phrases_ = other.phrases_; bitField0_ |= 0x00000001; } else { ensurePhrasesIsMutable(); phrases_.addAll(other.phrases_); } onChanged(); } if (other.getBoost() != 0F) { setBoost(other.getBoost()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); ensurePhrasesIsMutable(); phrases_.add(s); break; } // case 10 case 37: { boost_ = input.readFloat(); bitField0_ |= 0x00000002; break; } // case 37 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.LazyStringArrayList phrases_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensurePhrasesIsMutable() { if (!phrases_.isModifiable()) { phrases_ = new com.google.protobuf.LazyStringArrayList(phrases_); } bitField0_ |= 0x00000001; } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @return A list containing the phrases. */ public com.google.protobuf.ProtocolStringList getPhrasesList() { phrases_.makeImmutable(); return phrases_; } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @return The count of phrases. */ public int getPhrasesCount() { return phrases_.size(); } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param index The index of the element to return. * @return The phrases at the given index. */ public java.lang.String getPhrases(int index) { return phrases_.get(index); } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param index The index of the value to return. * @return The bytes of the phrases at the given index. */ public com.google.protobuf.ByteString getPhrasesBytes(int index) { return phrases_.getByteString(index); } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param index The index to set the value at. * @param value The phrases to set. * @return This builder for chaining. */ public Builder setPhrases(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePhrasesIsMutable(); phrases_.set(index, value); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param value The phrases to add. * @return This builder for chaining. */ public Builder addPhrases(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePhrasesIsMutable(); phrases_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param values The phrases to add. * @return This builder for chaining. */ public Builder addAllPhrases(java.lang.Iterable<java.lang.String> values) { ensurePhrasesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, phrases_); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @return This builder for chaining. */ public Builder clearPhrases() { phrases_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); ; onChanged(); return this; } /** * * * <pre> * A list of strings containing words and phrases "hints" so that * the speech recognition is more likely to recognize them. This can be used * to improve the accuracy for specific words and phrases, for example, if * specific commands are typically spoken by the user. This can also be used * to add additional words to the vocabulary of the recognizer. See * [usage limits](https://cloud.google.com/speech-to-text/quotas#content). * * List items can also be set to classes for groups of words that represent * common concepts that occur in natural language. For example, rather than * providing phrase hints for every month of the year, using the $MONTH class * improves the likelihood of correctly transcribing audio that includes * months. * </pre> * * <code>repeated string phrases = 1;</code> * * @param value The bytes of the phrases to add. * @return This builder for chaining. */ public Builder addPhrasesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensurePhrasesIsMutable(); phrases_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } private float boost_; /** * * * <pre> * Hint Boost. Positive value will increase the probability that a specific * phrase will be recognized over other similar sounding phrases. The higher * the boost, the higher the chance of false positive recognition as well. * Negative boost values would correspond to anti-biasing. Anti-biasing is not * enabled, so negative boost will simply be ignored. Though `boost` can * accept a wide range of positive values, most use cases are best served with * values between 0 and 20. We recommend using a binary search approach to * finding the optimal value for your use case. * </pre> * * <code>float boost = 4;</code> * * @return The boost. */ @java.lang.Override public float getBoost() { return boost_; } /** * * * <pre> * Hint Boost. Positive value will increase the probability that a specific * phrase will be recognized over other similar sounding phrases. The higher * the boost, the higher the chance of false positive recognition as well. * Negative boost values would correspond to anti-biasing. Anti-biasing is not * enabled, so negative boost will simply be ignored. Though `boost` can * accept a wide range of positive values, most use cases are best served with * values between 0 and 20. We recommend using a binary search approach to * finding the optimal value for your use case. * </pre> * * <code>float boost = 4;</code> * * @param value The boost to set. * @return This builder for chaining. */ public Builder setBoost(float value) { boost_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Hint Boost. Positive value will increase the probability that a specific * phrase will be recognized over other similar sounding phrases. The higher * the boost, the higher the chance of false positive recognition as well. * Negative boost values would correspond to anti-biasing. Anti-biasing is not * enabled, so negative boost will simply be ignored. Though `boost` can * accept a wide range of positive values, most use cases are best served with * values between 0 and 20. We recommend using a binary search approach to * finding the optimal value for your use case. * </pre> * * <code>float boost = 4;</code> * * @return This builder for chaining. */ public Builder clearBoost() { bitField0_ = (bitField0_ & ~0x00000002); boost_ = 0F; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.speech.v1.SpeechContext) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v1.SpeechContext) private static final com.google.cloud.speech.v1.SpeechContext DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v1.SpeechContext(); } public static com.google.cloud.speech.v1.SpeechContext getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SpeechContext> PARSER = new com.google.protobuf.AbstractParser<SpeechContext>() { @java.lang.Override public SpeechContext parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SpeechContext> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SpeechContext> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v1.SpeechContext getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/graal
36,585
compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CheckGraalInvariants.java
/* * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.graal.compiler.core.test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.graalvm.word.LocationIdentity; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import jdk.graal.compiler.api.replacements.Snippet; import jdk.graal.compiler.api.replacements.Snippet.ConstantParameter; import jdk.graal.compiler.api.replacements.Snippet.NonNullParameter; import jdk.graal.compiler.api.replacements.Snippet.VarargsParameter; import jdk.graal.compiler.api.test.Graal; import jdk.graal.compiler.api.test.ModuleSupport; import jdk.graal.compiler.bytecode.BridgeMethodUtils; import jdk.graal.compiler.core.CompilerThreadFactory; import jdk.graal.compiler.core.common.GraalOptions; import jdk.graal.compiler.core.common.LIRKind; import jdk.graal.compiler.core.common.type.ArithmeticOpTable; import jdk.graal.compiler.debug.DebugCloseable; import jdk.graal.compiler.debug.DebugContext; import jdk.graal.compiler.debug.DebugContext.Builder; import jdk.graal.compiler.debug.GraalError; import jdk.graal.compiler.graph.Node; import jdk.graal.compiler.graph.NodeClass; import jdk.graal.compiler.nodeinfo.NodeInfo; import jdk.graal.compiler.nodes.FrameState; import jdk.graal.compiler.nodes.PhiNode; import jdk.graal.compiler.nodes.StructuredGraph; import jdk.graal.compiler.nodes.StructuredGraph.AllowAssumptions; import jdk.graal.compiler.nodes.graphbuilderconf.ClassInitializationPlugin; import jdk.graal.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration; import jdk.graal.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins; import jdk.graal.compiler.nodes.graphbuilderconf.GraphBuilderContext; import jdk.graal.compiler.nodes.graphbuilderconf.InvocationPlugins; import jdk.graal.compiler.nodes.java.LoadFieldNode; import jdk.graal.compiler.nodes.java.MethodCallTargetNode; import jdk.graal.compiler.nodes.memory.MemoryKill; import jdk.graal.compiler.nodes.memory.MultiMemoryKill; import jdk.graal.compiler.nodes.memory.SingleMemoryKill; import jdk.graal.compiler.nodes.spi.CoreProviders; import jdk.graal.compiler.options.Option; import jdk.graal.compiler.options.OptionDescriptor; import jdk.graal.compiler.options.OptionDescriptors; import jdk.graal.compiler.options.OptionValues; import jdk.graal.compiler.options.OptionsParser; import jdk.graal.compiler.phases.OptimisticOptimizations; import jdk.graal.compiler.phases.PhaseSuite; import jdk.graal.compiler.phases.VerifyPhase; import jdk.graal.compiler.phases.VerifyPhase.VerificationError; import jdk.graal.compiler.phases.contract.VerifyNodeCosts; import jdk.graal.compiler.phases.tiers.HighTierContext; import jdk.graal.compiler.phases.util.Providers; import jdk.graal.compiler.runtime.RuntimeProvider; import jdk.graal.compiler.serviceprovider.GraalServices; import jdk.graal.compiler.test.AddExports; import jdk.graal.compiler.test.SubprocessUtil; import jdk.graal.compiler.util.EconomicHashMap; import jdk.graal.compiler.util.EconomicHashSet; import jdk.internal.misc.Unsafe; import jdk.vm.ci.code.BailoutException; import jdk.vm.ci.code.Register; import jdk.vm.ci.code.Register.RegisterCategory; import jdk.vm.ci.meta.ConstantPool; import jdk.vm.ci.meta.JavaField; import jdk.vm.ci.meta.JavaMethod; import jdk.vm.ci.meta.JavaType; import jdk.vm.ci.meta.MetaAccessProvider; import jdk.vm.ci.meta.ResolvedJavaField; import jdk.vm.ci.meta.ResolvedJavaMethod; import jdk.vm.ci.meta.ResolvedJavaType; import jdk.vm.ci.meta.SpeculationLog; import jdk.vm.ci.meta.Value; /** * Checks that all Graal classes comply with global invariants such as using * {@link Object#equals(Object)} to compare certain types instead of identity comparisons. */ @AddExports({"java.base/jdk.internal.misc"}) public class CheckGraalInvariants extends GraalCompilerTest { /** * Magic token to denote the classes in the Java runtime image (i.e. in the {@code jrt:/} file * system). */ public static final String JRT_CLASS_PATH_ENTRY = "<jrt>"; private static boolean shouldVerifyEquals(ResolvedJavaMethod m) { if (m.getName().equals("identityEquals")) { ResolvedJavaType c = m.getDeclaringClass(); if (c.getName().equals("Ljdk/vm/ci/meta/AbstractValue;") || c.getName().equals("jdk/vm/ci/meta/Value")) { return false; } } return true; } public static void main(String[] args) { } public static String relativeFileName(String absolutePath) { int lastFileSeparatorIndex = absolutePath.lastIndexOf(File.separator); return absolutePath.substring(Math.max(lastFileSeparatorIndex, 0)); } public static class InvariantsTool { protected boolean shouldProcess(String classpathEntry) { if (classpathEntry.equals(JRT_CLASS_PATH_ENTRY)) { return true; } if (classpathEntry.endsWith(".jar")) { String name = new File(classpathEntry).getName(); return name.contains("graal"); } return false; } Path getLibgraalJar() { assert shouldVerifyLibGraalInvariants(); String javaClassPath = System.getProperty("java.class.path"); if (javaClassPath != null) { String[] jcp = javaClassPath.split(File.pathSeparator); for (String s : jcp) { Path path = Path.of(s); if (s.endsWith(".jar")) { Path libgraal = path.getParent().resolve("libgraal.jar"); if (Files.exists(libgraal)) { return libgraal; } } } throw new AssertionError(String.format("Could not find libgraal.jar as sibling of a jar on java.class.path:%n %s", Stream.of(jcp).sorted().collect(Collectors.joining("\n ")))); } throw new AssertionError("The java.class.path system property is missing"); } protected List<String> getClassPath() { List<String> classpath = new ArrayList<>(); classpath.add(JRT_CLASS_PATH_ENTRY); String upgradeModulePath = System.getProperty("jdk.module.upgrade.path"); if (upgradeModulePath != null) { classpath.addAll(List.of(upgradeModulePath.split(File.pathSeparator))); } if (shouldVerifyLibGraalInvariants()) { classpath.add(getLibgraalJar().toString()); } return classpath; } protected boolean shouldLoadClass(String className) { if (className.equals("module-info") || className.startsWith("META-INF.versions.")) { return false; } return true; } public boolean shouldVerifyLibGraalInvariants() { return true; } public boolean shouldVerifyFoldableMethods() { return true; } public void verifyCurrentTimeMillis(MetaAccessProvider meta, MethodCallTargetNode t, ResolvedJavaType declaringClass) { final ResolvedJavaType services = meta.lookupJavaType(GraalServices.class); if (!declaringClass.equals(services)) { throw new VerificationError(t, "Should use System.nanoTime() for measuring elapsed time or GraalServices.milliTimeStamp() for the time since the epoch"); } } /** * Makes edits to the list of verifiers to be run. */ @SuppressWarnings("unused") protected void updateVerifiers(List<VerifyPhase<CoreProviders>> verifiers) { } /** * Determines if {@code option} should be checked to ensure it has at least one usage. */ public boolean shouldCheckUsage(OptionDescriptor option) { if (option.getOptionKey().getClass().isAnonymousClass()) { /* * A derived option. */ return false; } return true; } public boolean checkAssertions() { return true; } } @Test public void test() { Assume.assumeFalse("JaCoCo causes failure", SubprocessUtil.isJaCoCoAttached()); // GR-50672 assumeManagementLibraryIsLoadable(); runTest(new InvariantsTool()); } public static void runTest(InvariantsTool tool) { RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class); Providers providers = rt.getHostBackend().getProviders(); MetaAccessProvider metaAccess = providers.getMetaAccess(); PhaseSuite<HighTierContext> graphBuilderSuite = new PhaseSuite<>(); Plugins plugins = new Plugins(new InvocationPlugins()); plugins.setClassInitializationPlugin(new DoNotInitializeClassInitializationPlugin()); GraphBuilderConfiguration config = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true).withUnresolvedIsError(true); graphBuilderSuite.appendPhase(new TestGraphBuilderPhase(config)); HighTierContext context = new HighTierContext(providers, graphBuilderSuite, OptimisticOptimizations.NONE); Assume.assumeTrue(VerifyPhase.class.desiredAssertionStatus()); List<String> classPath = tool.getClassPath(); Assert.assertNotNull("Cannot find class path", classPath); final List<String> classNames = new ArrayList<>(); for (String path : classPath) { if (tool.shouldProcess(path)) { try { if (path.equals(JRT_CLASS_PATH_ENTRY)) { for (String className : ModuleSupport.getJRTGraalClassNames()) { if (isGSON(className) || isONNX(className)) { continue; } classNames.add(className); } } else { File file = new File(path); if (!file.exists()) { continue; } if (file.isDirectory()) { Path root = file.toPath(); Files.walk(root).forEach(p -> { String name = root.relativize(p).toString(); if (name.endsWith(".class") && !name.startsWith("META-INF/versions/")) { String className = name.substring(0, name.length() - ".class".length()).replace('/', '.'); if (!(isInNativeImage(className) || isGSON(className) || isONNX(className))) { classNames.add(className); } } }); } else { try (ZipFile zipFile = new ZipFile(file)) { for (final Enumeration<? extends ZipEntry> entry = zipFile.entries(); entry.hasMoreElements();) { final ZipEntry zipEntry = entry.nextElement(); String name = zipEntry.getName(); if (name.endsWith(".class") && !name.startsWith("META-INF/versions/")) { String className = name.substring(0, name.length() - ".class".length()).replace('/', '.'); if (isInNativeImage(className) || isGSON(className) || isONNX(className)) { continue; } classNames.add(className); } } } } } } catch (IOException ex) { throw new AssertionError(ex); } } } Assert.assertFalse("Could not find graal jars on class path: " + classPath, classNames.isEmpty()); // Allows a subset of methods to be checked through use of a system property String property = System.getProperty(CheckGraalInvariants.class.getName() + ".filters"); String[] filters = property == null ? null : property.split(","); OptionValues options = getInitialOptions(); CompilerThreadFactory factory = new CompilerThreadFactory("CheckInvariantsThread"); int availableProcessors = Runtime.getRuntime().availableProcessors(); ThreadPoolExecutor executor = new ThreadPoolExecutor(availableProcessors, availableProcessors, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), factory); List<String> errors = Collections.synchronizedList(new ArrayList<>()); List<VerifyPhase<CoreProviders>> verifiers = new ArrayList<>(); // If you add a new type to test here, be sure to add appropriate // methods to the BadUsageWithEquals class below verifiers.add(new VerifyUsageWithEquals(Value.class)); verifiers.add(new VerifyUsageWithEquals(Register.class)); verifiers.add(new VerifyUsageWithEquals(RegisterCategory.class)); verifiers.add(new VerifyUsageWithEquals(JavaType.class)); verifiers.add(new VerifyUsageWithEquals(JavaMethod.class)); verifiers.add(new VerifyUsageWithEquals(JavaField.class)); verifiers.add(new VerifyUsageWithEquals(LocationIdentity.class)); verifiers.add(new VerifyUsageWithEquals(LIRKind.class)); verifiers.add(new VerifyUsageWithEquals(ArithmeticOpTable.class)); verifiers.add(new VerifyUsageWithEquals(ArithmeticOpTable.Op.class)); verifiers.add(new VerifyUsageWithEquals(SpeculationLog.Speculation.class, SpeculationLog.NO_SPECULATION)); verifiers.add(new VerifySharedConstantEmptyArray()); verifiers.add(new VerifyDebugUsage()); verifiers.add(new VerifyVirtualizableUsage()); verifiers.add(new VerifyUpdateUsages()); verifiers.add(new VerifyWordFactoryUsage()); verifiers.add(new VerifyBailoutUsage()); verifiers.add(new VerifySystemPropertyUsage()); verifiers.add(new VerifyInstanceOfUsage()); verifiers.add(new VerifyGetOptionsUsage()); verifiers.add(new VerifyUnsafeAccess()); verifiers.add(new VerifyVariableCasts()); verifiers.add(new VerifyIterableNodeType()); verifiers.add(new VerifyArchUsageInPlugins()); verifiers.add(new VerifyStatelessPhases()); verifiers.add(new VerifyProfileMethodUsage()); verifiers.add(new VerifyMemoryKillCheck()); verifiers.add(new VerifySnippetProbabilities()); verifiers.add(new VerifyPluginFrameState()); verifiers.add(new VerifyGraphUniqueUsages()); verifiers.add(new VerifyEndlessLoops()); verifiers.add(new VerifyPhaseNoDirectRecursion()); verifiers.add(new VerifyStringCaseUsage()); verifiers.add(new VerifyMathAbs()); verifiers.add(new VerifyLoopInfo()); verifiers.add(new VerifyGuardsStageUsages()); verifiers.add(new VerifyAArch64RegisterUsages()); VerifyAssertionUsage assertionUsages = null; boolean checkAssertions = tool.checkAssertions(); if (checkAssertions) { assertionUsages = new VerifyAssertionUsage(metaAccess); verifiers.add(assertionUsages); } if (tool.shouldVerifyLibGraalInvariants()) { verifiers.add(new VerifyLibGraalContextChecks()); } loadVerifiers(verifiers); VerifyFoldableMethods foldableMethodsVerifier = new VerifyFoldableMethods(); if (tool.shouldVerifyFoldableMethods()) { verifiers.add(foldableMethodsVerifier); } verifiers.add(new VerifyCurrentTimeMillisUsage(tool)); tool.updateVerifiers(verifiers); for (Method m : BadUsageWithEquals.class.getDeclaredMethods()) { ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m); try (DebugContext debug = new Builder(options).build()) { StructuredGraph graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).method(method).build(); try (DebugCloseable _ = debug.disableIntercept(); DebugContext.Scope _ = debug.scope("CheckingGraph", graph, method)) { graphBuilderSuite.apply(graph, context); // update phi stamps graph.getNodes().filter(PhiNode.class).forEach(PhiNode::inferStamp); checkGraph(verifiers, context, graph); errors.add(String.format("Expected error while checking %s", m)); } catch (VerificationError e) { // expected! } catch (Throwable e) { errors.add(String.format("Error while checking %s:%n%s", m, printStackTraceToString(e))); } } } Map<ResolvedJavaField, Set<ResolvedJavaMethod>> optionFieldUsages = initOptionFieldUsagesMap(tool, metaAccess, errors); ResolvedJavaType optionDescriptorsType = metaAccess.lookupJavaType(OptionDescriptors.class); if (errors.isEmpty()) { ClassLoader cl = CheckGraalInvariants.class.getClassLoader(); if (tool.shouldVerifyLibGraalInvariants()) { URL[] urls = {toURL(tool.getLibgraalJar())}; cl = new URLClassLoader(urls, cl); } // Order outer classes before the inner classes classNames.sort(Comparator.naturalOrder()); List<Class<?>> classes = loadClasses(tool, metaAccess, classNames, cl); for (Class<?> c : classes) { String className = c.getName(); executor.execute(() -> { try { checkClass(c, metaAccess, verifiers); } catch (Throwable e) { errors.add(String.format("Error while checking %s:%n%s", className, printStackTraceToString(e))); } }); ResolvedJavaType type = metaAccess.lookupJavaType(c); List<ResolvedJavaMethod> methods = new ArrayList<>(); try { methods.addAll(Arrays.asList(type.getDeclaredMethods(false))); methods.addAll(Arrays.asList(type.getDeclaredConstructors(false))); } catch (Throwable e) { errors.add(String.format("Error while checking %s:%n%s", className, printStackTraceToString(e))); } ResolvedJavaMethod clinit = type.getClassInitializer(); if (clinit != null) { methods.add(clinit); } for (ResolvedJavaMethod method : methods) { if (Modifier.isNative(method.getModifiers()) || Modifier.isAbstract(method.getModifiers())) { // ignore } else { String methodName = className + "." + method.getName(); if (matches(filters, methodName)) { executor.execute(() -> { try (DebugContext debug = new Builder(options).build()) { boolean isSubstitution = method.getAnnotation(Snippet.class) != null; StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).setIsSubstitution(isSubstitution).build(); try (DebugCloseable _ = debug.disableIntercept(); DebugContext.Scope _ = debug.scope("CheckingGraph", graph, method)) { checkMethod(method); graphBuilderSuite.apply(graph, context); // update phi stamps graph.getNodes().filter(PhiNode.class).forEach(PhiNode::inferStamp); collectOptionFieldUsages(optionFieldUsages, optionDescriptorsType, method, graph); checkGraph(verifiers, context, graph); } catch (VerificationError e) { errors.add(e.getMessage()); } catch (BailoutException e) { // Graal bail outs on certain patterns in Java bytecode // (e.g., // unbalanced monitors introduced by jacoco). } catch (Throwable e) { errors.add(String.format("Error while checking %s:%n%s", methodName, printStackTraceToString(e))); } } }); } } } } executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException e1) { throw new RuntimeException(e1); } if (tool.shouldVerifyFoldableMethods()) { try { foldableMethodsVerifier.finish(); } catch (Throwable e) { errors.add(e.getMessage()); } } } if (assertionUsages != null) { assert checkAssertions; try { assertionUsages.postProcess(); } catch (Throwable e) { errors.add(e.getMessage()); } } checkOptionFieldUsages(errors, optionFieldUsages); if (!errors.isEmpty()) { StringBuilder msg = new StringBuilder(); String nl = String.format("%n"); for (String e : errors) { if (!msg.isEmpty()) { msg.append(nl); } msg.append(e); } Assert.fail(msg.toString()); } } private static URL toURL(Path path) { try { return path.toUri().toURL(); } catch (MalformedURLException e) { throw new GraalError(e); } } @SuppressWarnings("unchecked") private static void loadVerifiers(List<VerifyPhase<CoreProviders>> verifiers) { for (VerifyPhase<CoreProviders> verifier : ServiceLoader.load(VerifyPhase.class)) { verifiers.add(verifier); } } /** * Initializes a map from fields annotated with {@link Option} whose usages should be checked to * empty sets that will collect the methods accessing each field. * <p> * The sets are synchronized to support parallel processing of methods. */ private static Map<ResolvedJavaField, Set<ResolvedJavaMethod>> initOptionFieldUsagesMap(InvariantsTool tool, MetaAccessProvider metaAccess, List<String> errors) { Map<ResolvedJavaField, Set<ResolvedJavaMethod>> optionFields = new EconomicHashMap<>(); for (OptionDescriptors set : OptionsParser.getOptionsLoader()) { for (OptionDescriptor option : set) { if (tool.shouldCheckUsage(option)) { Class<?> declaringClass = option.getDeclaringClass(); try { Field javaField = declaringClass.getDeclaredField(option.getFieldName()); optionFields.put(metaAccess.lookupJavaField(javaField), Collections.synchronizedSet(new EconomicHashSet<>())); } catch (NoSuchFieldException e) { errors.add(e.toString()); } } } } return optionFields; } private static void collectOptionFieldUsages(Map<ResolvedJavaField, Set<ResolvedJavaMethod>> optionFields, ResolvedJavaType optionDescriptorsType, ResolvedJavaMethod method, StructuredGraph graph) { if (!optionDescriptorsType.isAssignableFrom(method.getDeclaringClass())) { for (LoadFieldNode lfn : graph.getNodes().filter(LoadFieldNode.class)) { ResolvedJavaField field = lfn.field(); Set<ResolvedJavaMethod> loads = optionFields.get(field); if (loads != null) { loads.add(graph.method()); } } } } private static void checkOptionFieldUsages(List<String> errors, Map<ResolvedJavaField, Set<ResolvedJavaMethod>> optionFieldUsages) { for (Map.Entry<ResolvedJavaField, Set<ResolvedJavaMethod>> e : optionFieldUsages.entrySet()) { if (e.getValue().isEmpty()) { if (e.getKey().format("%H.%n").equals(GraalOptions.VerifyPhases.getDescriptor().getLocation())) { // Special case: This option may only have downstream uses } else { errors.add("No uses found for " + e.getKey().format("%H.%n")); } } } } /** * Native Image is an external tool and does not need to follow the Graal invariants. */ private static boolean isInNativeImage(String className) { return className.startsWith("org.graalvm.nativeimage"); } /** * GSON classes are compiled with old JDK. */ private static boolean isGSON(String className) { return className.contains("com.google.gson"); } /** * ONNXRuntime: do not check for the svm invariants. */ private static boolean isONNX(String className) { return className.contains("ai.onnxruntime"); } private static List<Class<?>> loadClasses(InvariantsTool tool, MetaAccessProvider metaAccess, List<String> classNames, ClassLoader cl) { List<Class<?>> classes = new ArrayList<>(classNames.size()); for (String className : classNames) { if (!tool.shouldLoadClass(className)) { continue; } try { Class<?> c = Class.forName(className, false, cl); /* * Ensure all types are linked eagerly, so that we can access the bytecode of all * methods. */ ResolvedJavaType type = metaAccess.lookupJavaType(c); type.link(); if (Node.class.isAssignableFrom(c)) { /* * Eagerly initialize Node classes because the VerifyNodeCosts checker will * initialize them anyway, and doing it here eagerly while being single-threaded * avoids race conditions. */ Unsafe.getUnsafe().ensureClassInitialized(c); } classes.add(c); } catch (UnsupportedClassVersionError e) { // graal-test.jar can contain classes compiled for different Java versions } catch (Throwable t) { GraalError.shouldNotReachHere(t); // ExcludeFromJacocoGeneratedReport } } return classes; } /** * @param metaAccess * @param verifiers */ private static void checkClass(Class<?> c, MetaAccessProvider metaAccess, List<VerifyPhase<CoreProviders>> verifiers) { if (Node.class.isAssignableFrom(c)) { if (c.getAnnotation(NodeInfo.class) == null) { throw new AssertionError(String.format("Node subclass %s requires %s annotation", c.getName(), NodeClass.class.getSimpleName())); } VerifyNodeCosts.verifyNodeClass(c); // Any concrete class which implements MemoryKill must actually implement either // SingleMemoryKill or MultiMemoryKill. assert !MemoryKill.class.isAssignableFrom(c) || Modifier.isAbstract(c.getModifiers()) || SingleMemoryKill.class.isAssignableFrom(c) || MultiMemoryKill.class.isAssignableFrom(c) : c + " must inherit from either SingleMemoryKill or MultiMemoryKill"; } if (c.equals(DebugContext.class)) { try { // there are many log/logIndent methods, check the 2 most basic versions c.getDeclaredMethod("log", String.class); c.getDeclaredMethod("logAndIndent", String.class); } catch (NoSuchMethodException | SecurityException e) { throw new VerificationError("DebugContext misses basic log/logAndIndent methods", e); } } for (VerifyPhase<CoreProviders> verifier : verifiers) { verifier.verifyClass(c, metaAccess); } } private static void checkMethod(ResolvedJavaMethod method) { if (method.getAnnotation(Snippet.class) == null) { Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) { for (Annotation a : parameterAnnotations[i]) { Class<? extends Annotation> annotationType = a.annotationType(); if (annotationType == ConstantParameter.class || annotationType == VarargsParameter.class || annotationType == NonNullParameter.class) { VerificationError verificationError = new VerificationError("Parameter %d of %s is annotated with %s but the method is not annotated with %s", i, method, annotationType.getSimpleName(), Snippet.class.getSimpleName()); throw verificationError; } } } } } /** * Checks the invariants for a single graph. */ private static void checkGraph(List<VerifyPhase<CoreProviders>> verifiers, HighTierContext context, StructuredGraph graph) { for (VerifyPhase<CoreProviders> verifier : verifiers) { if (!(verifier instanceof VerifyUsageWithEquals) || shouldVerifyEquals(graph.method())) { verifier.apply(graph, context); } else { verifier.apply(graph, context); } } if (graph.method().isBridge()) { BridgeMethodUtils.getBridgedMethod(graph.method()); } } private static boolean matches(String[] filters, String s) { if (filters == null || filters.length == 0) { return true; } for (String filter : filters) { if (s.contains(filter)) { return true; } } return false; } private static String printStackTraceToString(Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } static class BadUsageWithEquals { Value aValue; Register aRegister; RegisterCategory aRegisterCategory; JavaType aJavaType; JavaField aJavaField; JavaMethod aJavaMethod; LocationIdentity aLocationIdentity; LIRKind aLIRKind; ArithmeticOpTable anArithmeticOpTable; ArithmeticOpTable.Op anArithmeticOpTableOp; static Value aStaticValue; static Register aStaticRegister; static RegisterCategory aStaticRegisterCategory; static JavaType aStaticJavaType; static JavaField aStaticJavaField; static JavaMethod aStaticJavaMethod; static LocationIdentity aStaticLocationIdentity; static LIRKind aStaticLIRKind; static ArithmeticOpTable aStaticArithmeticOpTable; static ArithmeticOpTable.Op aStaticArithmeticOpTableOp; boolean test01(Value f) { return aValue == f; } boolean test02(Register f) { return aRegister == f; } boolean test03(RegisterCategory f) { return aRegisterCategory == f; } boolean test04(JavaType f) { return aJavaType == f; } boolean test05(JavaField f) { return aJavaField == f; } boolean test06(JavaMethod f) { return aJavaMethod == f; } boolean test07(LocationIdentity f) { return aLocationIdentity == f; } boolean test08(LIRKind f) { return aLIRKind == f; } boolean test09(ArithmeticOpTable f) { return anArithmeticOpTable == f; } boolean test10(ArithmeticOpTable.Op f) { return anArithmeticOpTableOp == f; } boolean test12(Value f) { return aStaticValue == f; } boolean test13(Register f) { return aStaticRegister == f; } boolean test14(RegisterCategory f) { return aStaticRegisterCategory == f; } boolean test15(JavaType f) { return aStaticJavaType == f; } boolean test16(JavaField f) { return aStaticJavaField == f; } boolean test17(JavaMethod f) { return aStaticJavaMethod == f; } boolean test18(LocationIdentity f) { return aStaticLocationIdentity == f; } boolean test19(LIRKind f) { return aStaticLIRKind == f; } boolean test20(ArithmeticOpTable f) { return aStaticArithmeticOpTable == f; } boolean test21(ArithmeticOpTable.Op f) { return aStaticArithmeticOpTableOp == f; } } } class DoNotInitializeClassInitializationPlugin implements ClassInitializationPlugin { @Override public boolean supportsLazyInitialization(ConstantPool cp) { return true; } @Override public void loadReferencedType(GraphBuilderContext builder, ConstantPool cp, int cpi, int bytecode) { cp.loadReferencedType(cpi, bytecode, false); } @Override public boolean apply(GraphBuilderContext builder, ResolvedJavaType type, Supplier<FrameState> frameState) { return false; } }
googleapis/google-cloud-java
36,264
java-container/proto-google-cloud-container-v1/src/main/java/com/google/container/v1/SecurityPostureConfig.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1/cluster_service.proto // Protobuf Java Version: 3.25.8 package com.google.container.v1; /** * * * <pre> * SecurityPostureConfig defines the flags needed to enable/disable features for * the Security Posture API. * </pre> * * Protobuf type {@code google.container.v1.SecurityPostureConfig} */ public final class SecurityPostureConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1.SecurityPostureConfig) SecurityPostureConfigOrBuilder { private static final long serialVersionUID = 0L; // Use SecurityPostureConfig.newBuilder() to construct. private SecurityPostureConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SecurityPostureConfig() { mode_ = 0; vulnerabilityMode_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SecurityPostureConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_SecurityPostureConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_SecurityPostureConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.SecurityPostureConfig.class, com.google.container.v1.SecurityPostureConfig.Builder.class); } /** * * * <pre> * Mode defines enablement mode for GKE Security posture features. * </pre> * * Protobuf enum {@code google.container.v1.SecurityPostureConfig.Mode} */ public enum Mode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Default value not specified. * </pre> * * <code>MODE_UNSPECIFIED = 0;</code> */ MODE_UNSPECIFIED(0), /** * * * <pre> * Disables Security Posture features on the cluster. * </pre> * * <code>DISABLED = 1;</code> */ DISABLED(1), /** * * * <pre> * Applies Security Posture features on the cluster. * </pre> * * <code>BASIC = 2;</code> */ BASIC(2), /** * * * <pre> * Applies the Security Posture off cluster Enterprise level features. * </pre> * * <code>ENTERPRISE = 3;</code> */ ENTERPRISE(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Default value not specified. * </pre> * * <code>MODE_UNSPECIFIED = 0;</code> */ public static final int MODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Disables Security Posture features on the cluster. * </pre> * * <code>DISABLED = 1;</code> */ public static final int DISABLED_VALUE = 1; /** * * * <pre> * Applies Security Posture features on the cluster. * </pre> * * <code>BASIC = 2;</code> */ public static final int BASIC_VALUE = 2; /** * * * <pre> * Applies the Security Posture off cluster Enterprise level features. * </pre> * * <code>ENTERPRISE = 3;</code> */ public static final int ENTERPRISE_VALUE = 3; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Mode valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static Mode forNumber(int value) { switch (value) { case 0: return MODE_UNSPECIFIED; case 1: return DISABLED; case 2: return BASIC; case 3: return ENTERPRISE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Mode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Mode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Mode>() { public Mode findValueByNumber(int number) { return Mode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.container.v1.SecurityPostureConfig.getDescriptor().getEnumTypes().get(0); } private static final Mode[] VALUES = values(); public static Mode valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private Mode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.container.v1.SecurityPostureConfig.Mode) } /** * * * <pre> * VulnerabilityMode defines enablement mode for vulnerability scanning. * </pre> * * Protobuf enum {@code google.container.v1.SecurityPostureConfig.VulnerabilityMode} */ public enum VulnerabilityMode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Default value not specified. * </pre> * * <code>VULNERABILITY_MODE_UNSPECIFIED = 0;</code> */ VULNERABILITY_MODE_UNSPECIFIED(0), /** * * * <pre> * Disables vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_DISABLED = 1;</code> */ VULNERABILITY_DISABLED(1), /** * * * <pre> * Applies basic vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_BASIC = 2;</code> */ VULNERABILITY_BASIC(2), /** * * * <pre> * Applies the Security Posture's vulnerability on cluster Enterprise level * features. * </pre> * * <code>VULNERABILITY_ENTERPRISE = 3;</code> */ VULNERABILITY_ENTERPRISE(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Default value not specified. * </pre> * * <code>VULNERABILITY_MODE_UNSPECIFIED = 0;</code> */ public static final int VULNERABILITY_MODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Disables vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_DISABLED = 1;</code> */ public static final int VULNERABILITY_DISABLED_VALUE = 1; /** * * * <pre> * Applies basic vulnerability scanning on the cluster. * </pre> * * <code>VULNERABILITY_BASIC = 2;</code> */ public static final int VULNERABILITY_BASIC_VALUE = 2; /** * * * <pre> * Applies the Security Posture's vulnerability on cluster Enterprise level * features. * </pre> * * <code>VULNERABILITY_ENTERPRISE = 3;</code> */ public static final int VULNERABILITY_ENTERPRISE_VALUE = 3; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static VulnerabilityMode valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static VulnerabilityMode forNumber(int value) { switch (value) { case 0: return VULNERABILITY_MODE_UNSPECIFIED; case 1: return VULNERABILITY_DISABLED; case 2: return VULNERABILITY_BASIC; case 3: return VULNERABILITY_ENTERPRISE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<VulnerabilityMode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<VulnerabilityMode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<VulnerabilityMode>() { public VulnerabilityMode findValueByNumber(int number) { return VulnerabilityMode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.container.v1.SecurityPostureConfig.getDescriptor().getEnumTypes().get(1); } private static final VulnerabilityMode[] VALUES = values(); public static VulnerabilityMode valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private VulnerabilityMode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.container.v1.SecurityPostureConfig.VulnerabilityMode) } private int bitField0_; public static final int MODE_FIELD_NUMBER = 1; private int mode_ = 0; /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @return Whether the mode field is set. */ @java.lang.Override public boolean hasMode() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The enum numeric value on the wire for mode. */ @java.lang.Override public int getModeValue() { return mode_; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The mode. */ @java.lang.Override public com.google.container.v1.SecurityPostureConfig.Mode getMode() { com.google.container.v1.SecurityPostureConfig.Mode result = com.google.container.v1.SecurityPostureConfig.Mode.forNumber(mode_); return result == null ? com.google.container.v1.SecurityPostureConfig.Mode.UNRECOGNIZED : result; } public static final int VULNERABILITY_MODE_FIELD_NUMBER = 2; private int vulnerabilityMode_ = 0; /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return Whether the vulnerabilityMode field is set. */ @java.lang.Override public boolean hasVulnerabilityMode() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The enum numeric value on the wire for vulnerabilityMode. */ @java.lang.Override public int getVulnerabilityModeValue() { return vulnerabilityMode_; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The vulnerabilityMode. */ @java.lang.Override public com.google.container.v1.SecurityPostureConfig.VulnerabilityMode getVulnerabilityMode() { com.google.container.v1.SecurityPostureConfig.VulnerabilityMode result = com.google.container.v1.SecurityPostureConfig.VulnerabilityMode.forNumber( vulnerabilityMode_); return result == null ? com.google.container.v1.SecurityPostureConfig.VulnerabilityMode.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeEnum(1, mode_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeEnum(2, vulnerabilityMode_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, mode_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, vulnerabilityMode_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.container.v1.SecurityPostureConfig)) { return super.equals(obj); } com.google.container.v1.SecurityPostureConfig other = (com.google.container.v1.SecurityPostureConfig) obj; if (hasMode() != other.hasMode()) return false; if (hasMode()) { if (mode_ != other.mode_) return false; } if (hasVulnerabilityMode() != other.hasVulnerabilityMode()) return false; if (hasVulnerabilityMode()) { if (vulnerabilityMode_ != other.vulnerabilityMode_) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasMode()) { hash = (37 * hash) + MODE_FIELD_NUMBER; hash = (53 * hash) + mode_; } if (hasVulnerabilityMode()) { hash = (37 * hash) + VULNERABILITY_MODE_FIELD_NUMBER; hash = (53 * hash) + vulnerabilityMode_; } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1.SecurityPostureConfig parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.SecurityPostureConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.SecurityPostureConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.SecurityPostureConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.SecurityPostureConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.SecurityPostureConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.SecurityPostureConfig parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.SecurityPostureConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.SecurityPostureConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1.SecurityPostureConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.SecurityPostureConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.SecurityPostureConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.container.v1.SecurityPostureConfig prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * SecurityPostureConfig defines the flags needed to enable/disable features for * the Security Posture API. * </pre> * * Protobuf type {@code google.container.v1.SecurityPostureConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1.SecurityPostureConfig) com.google.container.v1.SecurityPostureConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_SecurityPostureConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_SecurityPostureConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.SecurityPostureConfig.class, com.google.container.v1.SecurityPostureConfig.Builder.class); } // Construct using com.google.container.v1.SecurityPostureConfig.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; mode_ = 0; vulnerabilityMode_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_SecurityPostureConfig_descriptor; } @java.lang.Override public com.google.container.v1.SecurityPostureConfig getDefaultInstanceForType() { return com.google.container.v1.SecurityPostureConfig.getDefaultInstance(); } @java.lang.Override public com.google.container.v1.SecurityPostureConfig build() { com.google.container.v1.SecurityPostureConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1.SecurityPostureConfig buildPartial() { com.google.container.v1.SecurityPostureConfig result = new com.google.container.v1.SecurityPostureConfig(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.container.v1.SecurityPostureConfig result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.mode_ = mode_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.vulnerabilityMode_ = vulnerabilityMode_; to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.container.v1.SecurityPostureConfig) { return mergeFrom((com.google.container.v1.SecurityPostureConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1.SecurityPostureConfig other) { if (other == com.google.container.v1.SecurityPostureConfig.getDefaultInstance()) return this; if (other.hasMode()) { setMode(other.getMode()); } if (other.hasVulnerabilityMode()) { setVulnerabilityMode(other.getVulnerabilityMode()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { mode_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { vulnerabilityMode_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int mode_ = 0; /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @return Whether the mode field is set. */ @java.lang.Override public boolean hasMode() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The enum numeric value on the wire for mode. */ @java.lang.Override public int getModeValue() { return mode_; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @param value The enum numeric value on the wire for mode to set. * @return This builder for chaining. */ public Builder setModeValue(int value) { mode_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @return The mode. */ @java.lang.Override public com.google.container.v1.SecurityPostureConfig.Mode getMode() { com.google.container.v1.SecurityPostureConfig.Mode result = com.google.container.v1.SecurityPostureConfig.Mode.forNumber(mode_); return result == null ? com.google.container.v1.SecurityPostureConfig.Mode.UNRECOGNIZED : result; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @param value The mode to set. * @return This builder for chaining. */ public Builder setMode(com.google.container.v1.SecurityPostureConfig.Mode value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; mode_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Sets which mode to use for Security Posture features. * </pre> * * <code>optional .google.container.v1.SecurityPostureConfig.Mode mode = 1;</code> * * @return This builder for chaining. */ public Builder clearMode() { bitField0_ = (bitField0_ & ~0x00000001); mode_ = 0; onChanged(); return this; } private int vulnerabilityMode_ = 0; /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return Whether the vulnerabilityMode field is set. */ @java.lang.Override public boolean hasVulnerabilityMode() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The enum numeric value on the wire for vulnerabilityMode. */ @java.lang.Override public int getVulnerabilityModeValue() { return vulnerabilityMode_; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @param value The enum numeric value on the wire for vulnerabilityMode to set. * @return This builder for chaining. */ public Builder setVulnerabilityModeValue(int value) { vulnerabilityMode_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return The vulnerabilityMode. */ @java.lang.Override public com.google.container.v1.SecurityPostureConfig.VulnerabilityMode getVulnerabilityMode() { com.google.container.v1.SecurityPostureConfig.VulnerabilityMode result = com.google.container.v1.SecurityPostureConfig.VulnerabilityMode.forNumber( vulnerabilityMode_); return result == null ? com.google.container.v1.SecurityPostureConfig.VulnerabilityMode.UNRECOGNIZED : result; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @param value The vulnerabilityMode to set. * @return This builder for chaining. */ public Builder setVulnerabilityMode( com.google.container.v1.SecurityPostureConfig.VulnerabilityMode value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; vulnerabilityMode_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Sets which mode to use for vulnerability scanning. * </pre> * * <code> * optional .google.container.v1.SecurityPostureConfig.VulnerabilityMode vulnerability_mode = 2; * </code> * * @return This builder for chaining. */ public Builder clearVulnerabilityMode() { bitField0_ = (bitField0_ & ~0x00000002); vulnerabilityMode_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.container.v1.SecurityPostureConfig) } // @@protoc_insertion_point(class_scope:google.container.v1.SecurityPostureConfig) private static final com.google.container.v1.SecurityPostureConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1.SecurityPostureConfig(); } public static com.google.container.v1.SecurityPostureConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SecurityPostureConfig> PARSER = new com.google.protobuf.AbstractParser<SecurityPostureConfig>() { @java.lang.Override public SecurityPostureConfig parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SecurityPostureConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SecurityPostureConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1.SecurityPostureConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/gobblin
36,644
gobblin-service/src/main/java/org/apache/gobblin/service/modules/scheduler/GobblinServiceJobScheduler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.service.modules.scheduler; import java.io.IOException; import java.net.URI; import java.text.ParseException; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import org.apache.commons.lang.StringUtils; import org.quartz.CronExpression; import org.quartz.DisallowConcurrentExecution; import org.quartz.InterruptableJob; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricFilter; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.collect.Maps; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.annotation.Alpha; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.instrumented.Instrumented; import org.apache.gobblin.metrics.ContextAwareMeter; import org.apache.gobblin.metrics.MetricContext; import org.apache.gobblin.metrics.ServiceMetricNames; import org.apache.gobblin.runtime.JobException; import org.apache.gobblin.runtime.api.FlowSpec; import org.apache.gobblin.runtime.api.Spec; import org.apache.gobblin.runtime.api.SpecCatalogListener; import org.apache.gobblin.runtime.api.SpecNotFoundException; import org.apache.gobblin.runtime.listeners.JobListener; import org.apache.gobblin.runtime.metrics.RuntimeMetrics; import org.apache.gobblin.runtime.spec_catalog.AddSpecResponse; import org.apache.gobblin.runtime.spec_catalog.FlowCatalog; import org.apache.gobblin.runtime.util.InjectionNames; import org.apache.gobblin.scheduler.BaseGobblinJob; import org.apache.gobblin.scheduler.JobScheduler; import org.apache.gobblin.scheduler.SchedulerService; import org.apache.gobblin.service.ServiceConfigKeys; import org.apache.gobblin.service.modules.flowgraph.Dag; import org.apache.gobblin.service.modules.orchestration.FlowLaunchHandler; import org.apache.gobblin.service.modules.orchestration.Orchestrator; import org.apache.gobblin.service.modules.orchestration.UserQuotaManager; import org.apache.gobblin.service.modules.spec.JobExecutionPlan; import org.apache.gobblin.util.ConfigUtils; import org.apache.gobblin.util.PropertiesUtils; import static org.apache.gobblin.service.ServiceConfigKeys.GOBBLIN_SERVICE_PREFIX; /** * An extension to {@link JobScheduler} that is also a {@link SpecCatalogListener}. * {@link GobblinServiceJobScheduler} listens for new / updated {@link FlowSpec} and schedules * and runs them via {@link Orchestrator}. */ @Alpha @Singleton @Slf4j public class GobblinServiceJobScheduler extends JobScheduler implements SpecCatalogListener { // Scheduler related configuration // A boolean function indicating if current instance will handle DR traffic or not. public static final String GOBBLIN_SERVICE_SCHEDULER_DR_NOMINATED = GOBBLIN_SERVICE_PREFIX + "drNominatedInstance"; protected final Logger _log; protected final FlowCatalog flowCatalog; protected final Orchestrator orchestrator; protected final UserQuotaManager quotaManager; protected final FlowLaunchHandler flowTriggerHandler; // todo - consider using JobScheduler::scheduledJobs in place of scheduledFlowSpecs @Getter protected final Map<String, FlowSpec> scheduledFlowSpecs; @Getter protected final Map<String, Long> lastUpdatedTimeForFlowSpec; protected volatile int loadSpecsBatchSize = -1; protected int skipSchedulingFlowsAfterNumDays; @Getter private volatile boolean isActive; private final String serviceName; private volatile Long perSpecGetRateValue = -1L; private volatile Long timeToInitializeSchedulerValue = -1L; private volatile Long timeToObtainSpecUrisValue = -1L; private volatile Long individualGetSpecSpeedValue = -1L; private volatile Long eachCompleteAddSpecValue = -1L; private volatile Long eachSpecCompilationValue = -1L; private volatile Long eachScheduleJobValue = -1L; private volatile Long totalGetSpecTimeValue = -1L; private volatile Long totalAddSpecTimeValue = -1L; private volatile int numJobsScheduledDuringStartupValue = -1; private static final MetricContext metricContext = Instrumented.getMetricContext(new org.apache.gobblin.configuration.State(), GobblinServiceJobScheduler.class); private static final ContextAwareMeter scheduledFlows = metricContext.contextAwareMeter(ServiceMetricNames.SCHEDULED_FLOW_METER); private static final ContextAwareMeter nonScheduledFlows = metricContext.contextAwareMeter(ServiceMetricNames.NON_SCHEDULED_FLOW_METER); /** * If current instances is nominated as a handler for DR traffic from down GaaS-Instance. * Note this is, currently, different from leadership change/fail-over handling, where the traffic could come * from GaaS instance out of current GaaS Cluster: * e.g. There are multi-datacenter deployment of GaaS Cluster. Intra-datacenter fail-over could be handled by * leadership change mechanism, while inter-datacenter fail-over would be handled by DR handling mechanism. */ private final boolean isNominatedDRHandler; /** * Use this to tag all DR-applicable FlowSpec entries in {@link org.apache.gobblin.runtime.api.SpecStore} * so only they would be loaded during DR handling. */ public static final String DR_FILTER_TAG = "dr"; @Inject public GobblinServiceJobScheduler(@Named(InjectionNames.SERVICE_NAME) String serviceName, Config config, FlowCatalog flowCatalog, Orchestrator orchestrator, SchedulerService schedulerService, UserQuotaManager quotaManager, Optional<Logger> log, FlowLaunchHandler flowTriggerHandler) throws Exception { super(ConfigUtils.configToProperties(config), schedulerService); _log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass()); this.serviceName = serviceName; this.flowCatalog = flowCatalog; this.orchestrator = orchestrator; this.scheduledFlowSpecs = Maps.newHashMap(); this.lastUpdatedTimeForFlowSpec = Maps.newHashMap(); this.loadSpecsBatchSize = Integer.parseInt(ConfigUtils.configToProperties(config).getProperty(ConfigurationKeys.LOAD_SPEC_BATCH_SIZE, String.valueOf(ConfigurationKeys.DEFAULT_LOAD_SPEC_BATCH_SIZE))); this.skipSchedulingFlowsAfterNumDays = Integer.parseInt(ConfigUtils.configToProperties(config).getProperty(ConfigurationKeys.SKIP_SCHEDULING_FLOWS_AFTER_NUM_DAYS, String.valueOf(ConfigurationKeys.DEFAULT_NUM_DAYS_TO_SKIP_AFTER))); this.isNominatedDRHandler = config.hasPath(GOBBLIN_SERVICE_SCHEDULER_DR_NOMINATED) && config.hasPath(GOBBLIN_SERVICE_SCHEDULER_DR_NOMINATED); this.quotaManager = quotaManager; this.flowTriggerHandler = flowTriggerHandler; // Check that these metrics do not exist before adding, mainly for testing purpose which creates multiple instances // of the scheduler. If one metric exists, then the others should as well. MetricFilter filter = MetricFilter.contains(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_GET_SPECS_DURING_STARTUP_PER_SPEC_RATE_NANOS); if (metricContext.getGauges(filter).isEmpty()) { metricContext.register(metricContext.newContextAwareGauge( RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_GET_SPECS_DURING_STARTUP_PER_SPEC_RATE_NANOS, () -> this.perSpecGetRateValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_LOAD_SPECS_BATCH_SIZE, () -> this.loadSpecsBatchSize)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_TIME_TO_INITIALIZE_SCHEDULER_NANOS, () -> this.timeToInitializeSchedulerValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_TIME_TO_OBTAIN_SPEC_URIS_NANOS, () -> timeToObtainSpecUrisValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_INDIVIDUAL_GET_SPEC_SPEED_NANOS, () -> individualGetSpecSpeedValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_EACH_COMPLETE_ADD_SPEC_NANOS, () -> eachCompleteAddSpecValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_EACH_SPEC_COMPILATION_NANOS, () -> eachSpecCompilationValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_EACH_SCHEDULE_JOB_NANOS, () -> eachScheduleJobValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_TOTAL_GET_SPEC_TIME_NANOS, () -> totalGetSpecTimeValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_TOTAL_ADD_SPEC_TIME_NANOS, () -> totalAddSpecTimeValue)); metricContext.register(metricContext.newContextAwareGauge(RuntimeMetrics.GOBBLIN_JOB_SCHEDULER_NUM_JOBS_SCHEDULED_DURING_STARTUP, () -> numJobsScheduledDuringStartupValue)); } } public synchronized void setActive(boolean isActive) { if (this.isActive == isActive) { // No-op if already in correct state return; } // Since we are going to change status to isActive=true, schedule all flows if (isActive) { // Need to set active=true first; otherwise in the onAddSpec(), node will forward specs to active node, which is itself. this.isActive = isActive; // Load spec asynchronously and make scheduler be aware of that. Thread scheduleSpec = new Thread(() -> { // Ensure compiler is healthy before attempting to schedule flows try { GobblinServiceJobScheduler.this.orchestrator.getSpecCompiler().awaitHealthy(); } catch (InterruptedException e) { throw new RuntimeException(e); } scheduleSpecsFromCatalog(); }); scheduleSpec.start(); } else { // Since we are going to change status to isActive=false, unschedule all flows try { this.scheduledFlowSpecs.clear(); unscheduleAllJobs(); } catch (SchedulerException e) { _log.error("Not all jobs were unscheduled", e); // We want to avoid duplicate flow execution, so fail loudly throw new RuntimeException(e); } // Need to set active=false at the end; otherwise in the onDeleteSpec(), node will forward specs to active node, which is itself. this.isActive = isActive; } } /** Return true if a spec should be scheduled and if it is, modify the spec of an adhoc flow before adding to * scheduler. Return false otherwise. */ private boolean addSpecHelperMethod(Spec spec) { // Adhoc flows will not have any job schedule key, but we should schedule them if (spec instanceof FlowSpec) { FlowSpec flowSpec = (FlowSpec) spec; if (!flowSpec.getConfig().hasPath(ConfigurationKeys.JOB_SCHEDULE_KEY) || isWithinRange( flowSpec.getConfig().getString(ConfigurationKeys.JOB_SCHEDULE_KEY), this.skipSchedulingFlowsAfterNumDays)) { // Disable FLOW_RUN_IMMEDIATELY on service startup or leadership change if the property is set to true if (PropertiesUtils.getPropAsBoolean(flowSpec.getConfigAsProperties(), ConfigurationKeys.FLOW_RUN_IMMEDIATELY, "false")) { Spec modifiedSpec = disableFlowRunImmediatelyOnStart((FlowSpec) spec); onAddSpec(modifiedSpec); } else { onAddSpec(spec); } return true; } }else { _log.debug("Not scheduling spec {} during startup as next job to schedule is outside of threshold.", spec); } return false; } /** * Returns true if next run for the given cron schedule is sooner than the threshold to skip scheduling after, false * otherwise. If the cron expression cannot be parsed and the next run cannot be calculated returns true to schedule. * @param cronExpression * @return num days until next run, max integer in the case it cannot be calculated */ @VisibleForTesting public static boolean isWithinRange(String cronExpression, int maxNumDaysToScheduleWithin) { if (cronExpression.trim().isEmpty()) { // If the cron expression is empty return true to capture adhoc flows return true; } CronExpression cron; Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); double numMillisInADay = 86400000; try { cron = new CronExpression(cronExpression); cron.setTimeZone(TimeZone.getTimeZone("UTC")); Date nextValidTimeAfter = cron.getNextValidTimeAfter(new Date()); if (nextValidTimeAfter == null) { log.warn("Next valid time doesn't exist since it's out of range for expression: {}. ", cronExpression); // nextValidTimeAfter will be null in cases only when CronExpression is outdated for a given range // this will cause NullPointerException while scheduling FlowSpecs from FlowCatalog // Hence, returning false to avoid expired flows from being scheduled return false; } cal.setTime(nextValidTimeAfter); long diff = cal.getTimeInMillis() - System.currentTimeMillis(); return (int) Math.round(diff / numMillisInADay) < maxNumDaysToScheduleWithin; } catch (ParseException e) { e.printStackTrace(); // Return false when a parsing exception occurs due to invalid cron return false; } } /** * Load all {@link FlowSpec}s from {@link FlowCatalog} as one of the initialization step, * and make schedulers be aware of that. * <p> * If it is newly brought up as the DR handler, will load additional FlowSpecs and handle transition properly. */ private void scheduleSpecsFromCatalog() { int numSpecs = this.flowCatalog.getSize(); int actualNumFlowsScheduled = 0; _log.info("Scheduling specs from catalog: {} flows in the catalog, will skip scheduling flows with next run after " + "{} days", numSpecs, this.skipSchedulingFlowsAfterNumDays); long startTime = System.nanoTime(); long totalGetTime = 0; long totalAddSpecTime = 0; Iterator<URI> uriIterator; HashSet<URI> urisLeftToSchedule = new HashSet<>(); try { uriIterator = this.flowCatalog.getSpecURIs(); while (uriIterator.hasNext()) { urisLeftToSchedule.add(uriIterator.next()); } } catch (IOException e) { throw new RuntimeException(e); } this.timeToObtainSpecUrisValue = System.nanoTime() - startTime; try { // If current instances nominated as DR handler, will take additional URIS from FlowCatalog. if (isNominatedDRHandler) { // Synchronously cleaning the execution state for DR-applicable FlowSpecs // before rescheduling the again in nominated DR-Hanlder. Iterator<URI> drUris = this.flowCatalog.getSpecURISWithTag(DR_FILTER_TAG); clearRunningFlowState(drUris); } } catch (IOException e) { throw new RuntimeException("Failed to get Spec URIs with tag to clear running flow state", e); } int startOffset = 0; long batchGetStartTime; long batchGetEndTime; while (startOffset < numSpecs) { batchGetStartTime = System.nanoTime(); Collection<Spec> batchOfSpecs = this.flowCatalog.getSpecsPaginated(startOffset, this.loadSpecsBatchSize); Iterator<Spec> batchOfSpecsIterator = batchOfSpecs.iterator(); batchGetEndTime = System.nanoTime(); while (batchOfSpecsIterator.hasNext()) { Spec spec = batchOfSpecsIterator.next(); try { if (addSpecHelperMethod(spec)) { totalAddSpecTime += this.eachCompleteAddSpecValue; // this is updated by each call to onAddSpec actualNumFlowsScheduled += 1; } } catch (Exception e) { // If there is an uncaught error thrown during compilation, log it and continue adding flows _log.error("Could not schedule spec {} from flowCatalog due to ", spec, e); } urisLeftToSchedule.remove(spec.getUri()); } startOffset += this.loadSpecsBatchSize; totalGetTime += batchGetEndTime - batchGetStartTime; // Don't skew the average get spec time value with the last batch that may be very small if (startOffset == 0 || batchOfSpecs.size() >= Math.round(0.75 * this.loadSpecsBatchSize)) { perSpecGetRateValue = (batchGetEndTime - batchGetStartTime) / batchOfSpecs.size(); } } // Ensure we did not miss any specs due to ordering changing (deletions/insertions) while loading Iterator<URI> urisLeft = urisLeftToSchedule.iterator(); long individualGetSpecStartTime; while (urisLeft.hasNext()) { URI uri = urisLeft.next(); try { individualGetSpecStartTime = System.nanoTime(); Spec spec = this.flowCatalog.getSpecWrapper(uri); this.individualGetSpecSpeedValue = System.nanoTime() - individualGetSpecStartTime; totalGetTime += this.individualGetSpecSpeedValue; if (addSpecHelperMethod(spec)) { totalAddSpecTime += this.eachCompleteAddSpecValue; // this is updated by each call to onAddSpec actualNumFlowsScheduled += 1; } } catch (Exception e) { // If there is an uncaught error thrown during compilation, log it and continue adding flows _log.error("Could not schedule spec uri {} from flowCatalog due to {}", uri, e); } } // Reset value after its last value to get an accurate reading this.perSpecGetRateValue = -1L; this.individualGetSpecSpeedValue = -1L; this.totalGetSpecTimeValue = totalGetTime; this.totalAddSpecTimeValue = totalAddSpecTime; this.numJobsScheduledDuringStartupValue = actualNumFlowsScheduled; this.flowCatalog.getMetrics().updateGetSpecTime(startTime); this.timeToInitializeSchedulerValue = System.nanoTime() - startTime; } /** * In DR-mode, the running {@link FlowSpec} will all be cancelled and rescheduled. * We will need to make sure that running {@link FlowSpec}s' state are cleared, and corresponding running jobs are * killed before rescheduling them. * @param drUris The uris that applicable for DR discovered from FlowCatalog. */ private void clearRunningFlowState(Iterator<URI> drUris) { while (drUris.hasNext()) { // TODO: Instead of simply call onDeleteSpec, a callback when FlowSpec is deleted from FlowCatalog, should also kill Azkaban Flow from AzkabanSpecProducer. onDeleteSpec(drUris.next(), FlowSpec.Builder.DEFAULT_VERSION); } } @VisibleForTesting protected static Spec disableFlowRunImmediatelyOnStart(FlowSpec spec) { Properties properties = spec.getConfigAsProperties(); properties.setProperty(ConfigurationKeys.FLOW_RUN_IMMEDIATELY, "false"); Config config = ConfigFactory.parseProperties(properties); return new FlowSpec(spec.getUri(), spec.getVersion(), spec.getDescription(), config, properties, spec.getTemplateURIs(), spec.getChildSpecs()); } @Override protected void startUp() throws Exception { super.startUp(); } /** * Synchronize the job scheduling because the same flowSpec can be scheduled by different threads. */ @Override public synchronized void scheduleJob(Properties jobProps, JobListener jobListener) throws JobException { Map<String, Object> additionalJobDataMap = Maps.newHashMap(); additionalJobDataMap.put(ServiceConfigKeys.GOBBLIN_SERVICE_FLOWSPEC, this.scheduledFlowSpecs.get(jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY))); try { scheduleJob(jobProps, jobListener, additionalJobDataMap, GobblinServiceJob.class); } catch (Exception e) { throw new JobException("Failed to schedule job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), e); } } @Override protected void logNewlyScheduledJob(JobDetail job, Trigger trigger) { Properties jobProps = (Properties) job.getJobDataMap().get(PROPERTIES_KEY); log.info(jobSchedulerTracePrefixBuilder(jobProps) + "nextTriggerTime: {} - Job newly scheduled", utcDateAsUTCEpochMillis(trigger.getNextFireTime())); } protected static String jobSchedulerTracePrefixBuilder(Properties jobProps) { return String.format("Scheduler trigger tracing (in epoch-ms UTC): [flowName: %s flowGroup: %s] - ", jobProps.getProperty(ConfigurationKeys.FLOW_NAME_KEY, "<<no flow name>>"), jobProps.getProperty(ConfigurationKeys.FLOW_GROUP_KEY, "<<no flow group>>")); } /** * Takes a Date object in UTC and returns the number of milliseconds since epoch * @param date */ public static long utcDateAsUTCEpochMillis(Date date) { return date.toInstant().toEpochMilli(); } @Override public void runJob(Properties jobProps, JobListener jobListener) throws JobException { try { FlowSpec flowSpec = this.scheduledFlowSpecs.get(jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY)); // The trigger event time will be missing for adhoc and run-immediately flows, so we set the default here String triggerTimestampMillis = jobProps.getProperty( ConfigurationKeys.ORCHESTRATOR_TRIGGER_EVENT_TIME_MILLIS_KEY, ConfigurationKeys.ORCHESTRATOR_TRIGGER_EVENT_TIME_DEFAULT_VAL); boolean isReminderEvent = Boolean.parseBoolean(jobProps.getProperty(ConfigurationKeys.FLOW_IS_REMINDER_EVENT_KEY, "false")); this.orchestrator.orchestrate(flowSpec, jobProps, Long.parseLong(triggerTimestampMillis), isReminderEvent); } catch (Exception e) { String exceptionPrefix = "Failed to run Spec: " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY); log.warn(exceptionPrefix + " because", e); throw new JobException(exceptionPrefix, e); } } /** * * @param addedSpec spec to be added * @return add spec response, which contains <code>null</code> if there is an error */ @Override public AddSpecResponse onAddSpec(Spec addedSpec) { long startTime = System.nanoTime(); _log.info("New Flow Spec detected: " + addedSpec); if (!(addedSpec instanceof FlowSpec)) { return null; } FlowSpec flowSpec = (FlowSpec) addedSpec; URI flowSpecUri = flowSpec.getUri(); Properties jobConfig = createJobConfig(flowSpec); boolean isExplain = flowSpec.isExplain(); String response = null; long compileStartTime = System.nanoTime(); // always try to compile the flow to verify if it is compilable Dag<JobExecutionPlan> dag = this.orchestrator.getSpecCompiler().compileFlow(flowSpec); this.eachSpecCompilationValue = System.nanoTime() - compileStartTime; // If dag is null then a compilation error has occurred if (dag != null && !dag.isEmpty()) { response = dag.toString(); } boolean compileSuccess = FlowCatalog.isCompileSuccessful(response); if (isExplain || !compileSuccess || !this.isActive) { // todo: in case of a scheduled job, we should also check if the job schedule is a valid cron schedule // so it can be scheduled _log.info("Ignoring the spec {}. isExplain: {}, compileSuccess: {}, master: {}", addedSpec, isExplain, compileSuccess, this.isActive); return new AddSpecResponse<>(response); } // Compare the modification timestamp of the spec being added if the scheduler is being initialized, ideally we // don't even want to do the same update twice as it will kill the existing flow and reschedule it unnecessarily Long modificationTime = Long.valueOf(flowSpec.getConfigAsProperties().getProperty(FlowSpec.MODIFICATION_TIME_KEY, "0")); String uriString = flowSpec.getUri().toString(); boolean isRunImmediately = PropertiesUtils.getPropAsBoolean(jobConfig, ConfigurationKeys.FLOW_RUN_IMMEDIATELY, "false"); // If the modification time is 0 (which means the original API was used to retrieve spec or warm standby mode is not // enabled), spec not in scheduler, or have a modification time associated with it assume it's the most recent if (modificationTime != 0L && this.scheduledFlowSpecs.containsKey(uriString) && this.lastUpdatedTimeForFlowSpec.containsKey(uriString)) { // For run-immediately flows with a schedule the modified_time would remain the same if (this.lastUpdatedTimeForFlowSpec.get(uriString).compareTo(modificationTime) > 0 || (this.lastUpdatedTimeForFlowSpec.get(uriString).equals(modificationTime) && !isRunImmediately)) { _log.warn("Ignoring the spec {} modified at time {} because we have a more updated version from time {}", addedSpec, modificationTime,this.lastUpdatedTimeForFlowSpec.get(uriString)); this.eachCompleteAddSpecValue = System.nanoTime() - startTime; return new AddSpecResponse<>(response); } } // todo : we should probably not schedule a flow if it is a runOnce flow this.scheduledFlowSpecs.put(flowSpecUri.toString(), flowSpec); this.lastUpdatedTimeForFlowSpec.put(flowSpecUri.toString(), modificationTime); if (jobConfig.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY)) { _log.info("{} Scheduling flow spec: {} ", this.serviceName, addedSpec); try { long scheduleStartTime = System.nanoTime(); scheduleJob(jobConfig, null); this.eachScheduleJobValue = System.nanoTime() - scheduleStartTime; } catch (JobException je) { _log.error("{} Failed to schedule or run FlowSpec {}", serviceName, addedSpec, je); this.scheduledFlowSpecs.remove(addedSpec.getUri().toString()); this.lastUpdatedTimeForFlowSpec.remove(flowSpecUri.toString()); this.eachCompleteAddSpecValue = System.nanoTime() - startTime; return null; } if (PropertiesUtils.getPropAsBoolean(jobConfig, ConfigurationKeys.FLOW_RUN_IMMEDIATELY, "false")) { _log.info("RunImmediately requested, hence executing FlowSpec: " + addedSpec); this.jobExecutor.execute(new NonScheduledJobRunner(flowSpecUri, false, jobConfig, null)); } } else { _log.info("No FlowSpec schedule found, so running FlowSpec: " + addedSpec); this.jobExecutor.execute(new NonScheduledJobRunner(flowSpecUri, true, jobConfig, null)); } this.eachCompleteAddSpecValue = System.nanoTime() - startTime; return new AddSpecResponse<>(response); } /** * Remove a flowSpec from schedule * Unlike onDeleteSpec, we want to avoid deleting the flowSpec on the executor * and we still want to unschedule if we cannot connect to zookeeper as the current node cannot be the master * @param specURI * @param specVersion */ private boolean unscheduleSpec(URI specURI, String specVersion) throws JobException { if (this.scheduledFlowSpecs.containsKey(specURI.toString())) { _log.info("Unscheduling flowSpec " + specURI + "/" + specVersion); this.scheduledFlowSpecs.remove(specURI.toString()); this.lastUpdatedTimeForFlowSpec.remove(specURI.toString()); unscheduleJob(specURI.toString()); try { FlowSpec spec = this.flowCatalog.getSpecs(specURI); Properties properties = spec.getConfigAsProperties(); _log.info(jobSchedulerTracePrefixBuilder(properties) + "Unscheduled Spec"); } catch (SpecNotFoundException e) { _log.warn("Unable to retrieve spec for URI {}", specURI); } return true; } else { _log.info(String.format( "Spec with URI: %s was not found in cache. Maybe it was cleaned, if not please clean it manually", specURI)); return false; } } public void onDeleteSpec(URI deletedSpecURI, String deletedSpecVersion) { onDeleteSpec(deletedSpecURI, deletedSpecVersion, new Properties()); } /** {@inheritDoc} */ @Override public void onDeleteSpec(URI deletedSpecURI, String deletedSpecVersion, Properties headers) { _log.info("Spec deletion detected: " + deletedSpecURI + "/" + deletedSpecVersion); if (!this.isActive) { _log.info("Skipping deletion of this spec {}/{} for non-leader host", deletedSpecURI, deletedSpecVersion); return; } try { Spec deletedSpec = this.scheduledFlowSpecs.get(deletedSpecURI.toString()); if (unscheduleSpec(deletedSpecURI, deletedSpecVersion)) { this.orchestrator.remove(deletedSpec, headers); } } catch (JobException | IOException e) { _log.warn(String.format("Spec with URI: %s was not unscheduled cleaning", deletedSpecURI), e); } } /** {@inheritDoc} */ @Override public void onUpdateSpec(Spec updatedSpec) { _log.info("Spec changed: " + updatedSpec); if (!(updatedSpec instanceof FlowSpec)) { return; } try { onAddSpec(updatedSpec); } catch (Exception e) { _log.error("Failed to update Spec: " + updatedSpec, e); } } private Properties createJobConfig(FlowSpec flowSpec) { Properties jobConfig = new Properties(); Properties flowSpecProperties = flowSpec.getConfigAsProperties(); jobConfig.putAll(this.properties); jobConfig.setProperty(ConfigurationKeys.JOB_NAME_KEY, flowSpec.getUri().toString()); jobConfig.setProperty(ConfigurationKeys.JOB_GROUP_KEY, flowSpec.getConfig().getValue(ConfigurationKeys.FLOW_GROUP_KEY).toString()); jobConfig.setProperty(ConfigurationKeys.FLOW_RUN_IMMEDIATELY, ConfigUtils.getString((flowSpec).getConfig(), ConfigurationKeys.FLOW_RUN_IMMEDIATELY, "false")); // todo : we should check if the job schedule is a valid cron schedule if (flowSpecProperties.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY) && StringUtils.isNotBlank( flowSpecProperties.getProperty(ConfigurationKeys.JOB_SCHEDULE_KEY))) { jobConfig.setProperty(ConfigurationKeys.JOB_SCHEDULE_KEY, flowSpecProperties.getProperty(ConfigurationKeys.JOB_SCHEDULE_KEY)); } // Note: the default values for missing flow name/group are different than the ones above to easily identify where // the values are not present initially jobConfig.setProperty(ConfigurationKeys.FLOW_NAME_KEY, flowSpecProperties.getProperty(ConfigurationKeys.FLOW_NAME_KEY, "<<missing flow name>>")); jobConfig.setProperty(ConfigurationKeys.FLOW_GROUP_KEY, flowSpecProperties.getProperty(ConfigurationKeys.FLOW_GROUP_KEY, "<<missing flow group>>")); return jobConfig; } /** * A Gobblin job to be scheduled. */ @DisallowConcurrentExecution @Slf4j public static class GobblinServiceJob extends BaseGobblinJob implements InterruptableJob { private static final Logger _log = LoggerFactory.getLogger(GobblinServiceJob.class); @Override public void executeImpl(JobExecutionContext context) throws JobExecutionException { try { // TODO: move this out of the try clause after location NPE source JobDetail jobDetail = context.getJobDetail(); _log.info("Starting FlowSpec " + jobDetail.getKey()); JobDataMap dataMap = jobDetail.getJobDataMap(); JobScheduler jobScheduler = (JobScheduler) dataMap.get(JOB_SCHEDULER_KEY); Properties jobProps = (Properties) dataMap.get(PROPERTIES_KEY); JobListener jobListener = (JobListener) dataMap.get(JOB_LISTENER_KEY); // Obtain trigger timestamp from trigger to pass to jobProps Trigger trigger = context.getTrigger(); // THIS current event has already fired if this method is called, so it now exists in <previousFireTime> long triggerTimeMillis = utcDateAsUTCEpochMillis(trigger.getPreviousFireTime()); // If the trigger is a reminder type event then utilize the trigger time saved in job properties rather than the // actual firing time if (jobDetail.getKey().getName().contains("reminder")) { String preservedConsensusEventTime = jobProps.getProperty( ConfigurationKeys.SCHEDULER_PRESERVED_CONSENSUS_EVENT_TIME_MILLIS_KEY, "0"); String expectedReminderTime = jobProps.getProperty( ConfigurationKeys.SCHEDULER_EXPECTED_REMINDER_TIME_MILLIS_KEY, "0"); _log.info(jobSchedulerTracePrefixBuilder(jobProps) + "triggerTime: {} expectedReminderTime: {} - Reminder job" + " triggered by scheduler at {}", preservedConsensusEventTime, expectedReminderTime, triggerTimeMillis); // TODO: add a metric if expected reminder time far exceeds system time jobProps.setProperty(ConfigurationKeys.ORCHESTRATOR_TRIGGER_EVENT_TIME_MILLIS_KEY, preservedConsensusEventTime); } else { jobProps.setProperty(ConfigurationKeys.ORCHESTRATOR_TRIGGER_EVENT_TIME_MILLIS_KEY, String.valueOf(triggerTimeMillis)); if (trigger.getNextFireTime() == null) { _log.info( jobSchedulerTracePrefixBuilder(jobProps) + "triggerTime: {} nextTriggerTime: NA - Job triggered by " + "scheduler", triggerTimeMillis); } else { _log.info( jobSchedulerTracePrefixBuilder(jobProps) + "triggerTime: {} nextTriggerTime: {} - Job triggered by " + "scheduler", triggerTimeMillis, utcDateAsUTCEpochMillis(trigger.getNextFireTime())); } } jobScheduler.runJob(jobProps, jobListener); } catch (Throwable t) { if (t instanceof NullPointerException) { log.warn("NullPointerException encountered while trying to execute flow. Message: " + t.getMessage(), t); } throw new JobExecutionException(t); } finally { scheduledFlows.mark(); } } @Override public void interrupt() { log.info("Job was interrupted"); } } /** * This class is responsible for running non-scheduled jobs. */ class NonScheduledJobRunner implements Runnable { private final URI specUri; private final Properties jobConfig; private final JobListener jobListener; private final boolean removeSpec; public NonScheduledJobRunner(URI uri, boolean removeSpec, Properties jobConfig, JobListener jobListener) { this.specUri = uri; this.jobConfig = jobConfig; this.jobListener = jobListener; this.removeSpec = removeSpec; } @Override public void run() { try { GobblinServiceJobScheduler.this.runJob(this.jobConfig, this.jobListener); if (removeSpec) { Object syncObject = GobblinServiceJobScheduler.this.flowCatalog.getSyncObject(specUri.toString()); if (syncObject != null) { // if the sync object does not exist, this job must be set to run due to job submission at service restart synchronized (syncObject) { while (!GobblinServiceJobScheduler.this.flowCatalog.exists(specUri)) { syncObject.wait(); } } } GobblinServiceJobScheduler.this.scheduledFlowSpecs.remove(specUri.toString()); GobblinServiceJobScheduler.this.lastUpdatedTimeForFlowSpec.remove(specUri.toString()); } } catch (JobException je) { _log.error("Failed to run job " + this.jobConfig.getProperty(ConfigurationKeys.JOB_NAME_KEY), je); } catch (InterruptedException e) { _log.error("Failed to delete the spec " + specUri, e); } finally { nonScheduledFlows.mark(); } } } }
googleapis/google-cloud-java
36,397
java-analyticshub/proto-google-cloud-analyticshub-v1/src/main/java/com/google/cloud/bigquery/analyticshub/v1/UpdateDataExchangeRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/analyticshub/v1/analyticshub.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.bigquery.analyticshub.v1; /** * * * <pre> * Message for updating a data exchange. * </pre> * * Protobuf type {@code google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest} */ public final class UpdateDataExchangeRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest) UpdateDataExchangeRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateDataExchangeRequest.newBuilder() to construct. private UpdateDataExchangeRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateDataExchangeRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateDataExchangeRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_UpdateDataExchangeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_UpdateDataExchangeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest.class, com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest.Builder.class); } private int bitField0_; public static final int UPDATE_MASK_FIELD_NUMBER = 1; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } public static final int DATA_EXCHANGE_FIELD_NUMBER = 2; private com.google.cloud.bigquery.analyticshub.v1.DataExchange dataExchange_; /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the dataExchange field is set. */ @java.lang.Override public boolean hasDataExchange() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The dataExchange. */ @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.DataExchange getDataExchange() { return dataExchange_ == null ? com.google.cloud.bigquery.analyticshub.v1.DataExchange.getDefaultInstance() : dataExchange_; } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.DataExchangeOrBuilder getDataExchangeOrBuilder() { return dataExchange_ == null ? com.google.cloud.bigquery.analyticshub.v1.DataExchange.getDefaultInstance() : dataExchange_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getDataExchange()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getDataExchange()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest)) { return super.equals(obj); } com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest other = (com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (hasDataExchange() != other.hasDataExchange()) return false; if (hasDataExchange()) { if (!getDataExchange().equals(other.getDataExchange())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } if (hasDataExchange()) { hash = (37 * hash) + DATA_EXCHANGE_FIELD_NUMBER; hash = (53 * hash) + getDataExchange().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message for updating a data exchange. * </pre> * * Protobuf type {@code google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest) com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_UpdateDataExchangeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_UpdateDataExchangeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest.class, com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest.Builder.class); } // Construct using // com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getUpdateMaskFieldBuilder(); getDataExchangeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } dataExchange_ = null; if (dataExchangeBuilder_ != null) { dataExchangeBuilder_.dispose(); dataExchangeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubProto .internal_static_google_cloud_bigquery_analyticshub_v1_UpdateDataExchangeRequest_descriptor; } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest getDefaultInstanceForType() { return com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest build() { com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest buildPartial() { com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest result = new com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.dataExchange_ = dataExchangeBuilder_ == null ? dataExchange_ : dataExchangeBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest) { return mergeFrom( (com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest other) { if (other == com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest .getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.hasDataExchange()) { mergeDataExchange(other.getDataExchange()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getDataExchangeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000001); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000001; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. Field mask specifies the fields to update in the data exchange * resource. The fields specified in the * `updateMask` are relative to the resource and are not a full request. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private com.google.cloud.bigquery.analyticshub.v1.DataExchange dataExchange_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.analyticshub.v1.DataExchange, com.google.cloud.bigquery.analyticshub.v1.DataExchange.Builder, com.google.cloud.bigquery.analyticshub.v1.DataExchangeOrBuilder> dataExchangeBuilder_; /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the dataExchange field is set. */ public boolean hasDataExchange() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The dataExchange. */ public com.google.cloud.bigquery.analyticshub.v1.DataExchange getDataExchange() { if (dataExchangeBuilder_ == null) { return dataExchange_ == null ? com.google.cloud.bigquery.analyticshub.v1.DataExchange.getDefaultInstance() : dataExchange_; } else { return dataExchangeBuilder_.getMessage(); } } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDataExchange(com.google.cloud.bigquery.analyticshub.v1.DataExchange value) { if (dataExchangeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } dataExchange_ = value; } else { dataExchangeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDataExchange( com.google.cloud.bigquery.analyticshub.v1.DataExchange.Builder builderForValue) { if (dataExchangeBuilder_ == null) { dataExchange_ = builderForValue.build(); } else { dataExchangeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeDataExchange(com.google.cloud.bigquery.analyticshub.v1.DataExchange value) { if (dataExchangeBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && dataExchange_ != null && dataExchange_ != com.google.cloud.bigquery.analyticshub.v1.DataExchange.getDefaultInstance()) { getDataExchangeBuilder().mergeFrom(value); } else { dataExchange_ = value; } } else { dataExchangeBuilder_.mergeFrom(value); } if (dataExchange_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearDataExchange() { bitField0_ = (bitField0_ & ~0x00000002); dataExchange_ = null; if (dataExchangeBuilder_ != null) { dataExchangeBuilder_.dispose(); dataExchangeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.bigquery.analyticshub.v1.DataExchange.Builder getDataExchangeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getDataExchangeFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.bigquery.analyticshub.v1.DataExchangeOrBuilder getDataExchangeOrBuilder() { if (dataExchangeBuilder_ != null) { return dataExchangeBuilder_.getMessageOrBuilder(); } else { return dataExchange_ == null ? com.google.cloud.bigquery.analyticshub.v1.DataExchange.getDefaultInstance() : dataExchange_; } } /** * * * <pre> * Required. The data exchange to update. * </pre> * * <code> * .google.cloud.bigquery.analyticshub.v1.DataExchange data_exchange = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.analyticshub.v1.DataExchange, com.google.cloud.bigquery.analyticshub.v1.DataExchange.Builder, com.google.cloud.bigquery.analyticshub.v1.DataExchangeOrBuilder> getDataExchangeFieldBuilder() { if (dataExchangeBuilder_ == null) { dataExchangeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.analyticshub.v1.DataExchange, com.google.cloud.bigquery.analyticshub.v1.DataExchange.Builder, com.google.cloud.bigquery.analyticshub.v1.DataExchangeOrBuilder>( getDataExchange(), getParentForChildren(), isClean()); dataExchange_ = null; } return dataExchangeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest) private static final com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest(); } public static com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateDataExchangeRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateDataExchangeRequest>() { @java.lang.Override public UpdateDataExchangeRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UpdateDataExchangeRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateDataExchangeRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.analyticshub.v1.UpdateDataExchangeRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,298
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetIamPolicyRegionBackendServiceRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.compute.v1; /** * * * <pre> * A request message for RegionBackendServices.GetIamPolicy. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest} */ public final class GetIamPolicyRegionBackendServiceRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest) GetIamPolicyRegionBackendServiceRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetIamPolicyRegionBackendServiceRequest.newBuilder() to construct. private GetIamPolicyRegionBackendServiceRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetIamPolicyRegionBackendServiceRequest() { project_ = ""; region_ = ""; resource_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GetIamPolicyRegionBackendServiceRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyRegionBackendServiceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyRegionBackendServiceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest.class, com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest.Builder.class); } private int bitField0_; public static final int OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER = 499220029; private int optionsRequestedPolicyVersion_ = 0; /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return Whether the optionsRequestedPolicyVersion field is set. */ @java.lang.Override public boolean hasOptionsRequestedPolicyVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return The optionsRequestedPolicyVersion. */ @java.lang.Override public int getOptionsRequestedPolicyVersion() { return optionsRequestedPolicyVersion_; } public static final int PROJECT_FIELD_NUMBER = 227560217; @SuppressWarnings("serial") private volatile java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REGION_FIELD_NUMBER = 138946292; @SuppressWarnings("serial") private volatile java.lang.Object region_ = ""; /** * * * <pre> * The name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The region. */ @java.lang.Override public java.lang.String getRegion() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } } /** * * * <pre> * The name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for region. */ @java.lang.Override public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RESOURCE_FIELD_NUMBER = 195806222; @SuppressWarnings("serial") private volatile java.lang.Object resource_ = ""; /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The resource. */ @java.lang.Override public java.lang.String getResource() { java.lang.Object ref = resource_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resource_ = s; return s; } } /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for resource. */ @java.lang.Override public com.google.protobuf.ByteString getResourceBytes() { java.lang.Object ref = resource_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resource_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 138946292, region_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 195806222, resource_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeInt32(499220029, optionsRequestedPolicyVersion_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(138946292, region_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(195806222, resource_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size( 499220029, optionsRequestedPolicyVersion_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest other = (com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest) obj; if (hasOptionsRequestedPolicyVersion() != other.hasOptionsRequestedPolicyVersion()) return false; if (hasOptionsRequestedPolicyVersion()) { if (getOptionsRequestedPolicyVersion() != other.getOptionsRequestedPolicyVersion()) return false; } if (!getProject().equals(other.getProject())) return false; if (!getRegion().equals(other.getRegion())) return false; if (!getResource().equals(other.getResource())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasOptionsRequestedPolicyVersion()) { hash = (37 * hash) + OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER; hash = (53 * hash) + getOptionsRequestedPolicyVersion(); } hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); hash = (37 * hash) + REGION_FIELD_NUMBER; hash = (53 * hash) + getRegion().hashCode(); hash = (37 * hash) + RESOURCE_FIELD_NUMBER; hash = (53 * hash) + getResource().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A request message for RegionBackendServices.GetIamPolicy. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest) com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyRegionBackendServiceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyRegionBackendServiceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest.class, com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest.Builder.class); } // Construct using // com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; optionsRequestedPolicyVersion_ = 0; project_ = ""; region_ = ""; resource_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyRegionBackendServiceRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest build() { com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest buildPartial() { com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest result = new com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.optionsRequestedPolicyVersion_ = optionsRequestedPolicyVersion_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.project_ = project_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.region_ = region_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.resource_ = resource_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest) { return mergeFrom( (com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest other) { if (other == com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest .getDefaultInstance()) return this; if (other.hasOptionsRequestedPolicyVersion()) { setOptionsRequestedPolicyVersion(other.getOptionsRequestedPolicyVersion()); } if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getRegion().isEmpty()) { region_ = other.region_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getResource().isEmpty()) { resource_ = other.resource_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 1111570338: { region_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 1111570338 case 1566449778: { resource_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 1566449778 case 1820481738: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 1820481738 case -301207064: { optionsRequestedPolicyVersion_ = input.readInt32(); bitField0_ |= 0x00000001; break; } // case -301207064 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int optionsRequestedPolicyVersion_; /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return Whether the optionsRequestedPolicyVersion field is set. */ @java.lang.Override public boolean hasOptionsRequestedPolicyVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return The optionsRequestedPolicyVersion. */ @java.lang.Override public int getOptionsRequestedPolicyVersion() { return optionsRequestedPolicyVersion_; } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @param value The optionsRequestedPolicyVersion to set. * @return This builder for chaining. */ public Builder setOptionsRequestedPolicyVersion(int value) { optionsRequestedPolicyVersion_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return This builder for chaining. */ public Builder clearOptionsRequestedPolicyVersion() { bitField0_ = (bitField0_ & ~0x00000001); optionsRequestedPolicyVersion_ = 0; onChanged(); return this; } private java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ public java.lang.String getProject() { java.lang.Object ref = project_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for project to set. * @return This builder for chaining. */ public Builder setProjectBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object region_ = ""; /** * * * <pre> * The name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The region. */ public java.lang.String getRegion() { java.lang.Object ref = region_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for region. */ public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The region to set. * @return This builder for chaining. */ public Builder setRegion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } region_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearRegion() { region_ = getDefaultInstance().getRegion(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * The name of the region for this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for region to set. * @return This builder for chaining. */ public Builder setRegionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); region_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object resource_ = ""; /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The resource. */ public java.lang.String getResource() { java.lang.Object ref = resource_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resource_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for resource. */ public com.google.protobuf.ByteString getResourceBytes() { java.lang.Object ref = resource_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resource_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The resource to set. * @return This builder for chaining. */ public Builder setResource(java.lang.String value) { if (value == null) { throw new NullPointerException(); } resource_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearResource() { resource_ = getDefaultInstance().getResource(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Name or id of the resource for this request. * </pre> * * <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for resource to set. * @return This builder for chaining. */ public Builder setResourceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resource_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest) private static final com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest(); } public static com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GetIamPolicyRegionBackendServiceRequest> PARSER = new com.google.protobuf.AbstractParser<GetIamPolicyRegionBackendServiceRequest>() { @java.lang.Override public GetIamPolicyRegionBackendServiceRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<GetIamPolicyRegionBackendServiceRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetIamPolicyRegionBackendServiceRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyRegionBackendServiceRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,309
java-networkservices/proto-google-cloud-networkservices-v1/src/main/java/com/google/cloud/networkservices/v1/CreateTcpRouteRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/networkservices/v1/tcp_route.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.networkservices.v1; /** * * * <pre> * Request used by the TcpRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateTcpRouteRequest} */ public final class CreateTcpRouteRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.networkservices.v1.CreateTcpRouteRequest) CreateTcpRouteRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateTcpRouteRequest.newBuilder() to construct. private CreateTcpRouteRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateTcpRouteRequest() { parent_ = ""; tcpRouteId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateTcpRouteRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.TcpRouteProto .internal_static_google_cloud_networkservices_v1_CreateTcpRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.TcpRouteProto .internal_static_google_cloud_networkservices_v1_CreateTcpRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateTcpRouteRequest.class, com.google.cloud.networkservices.v1.CreateTcpRouteRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the TcpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource of the TcpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TCP_ROUTE_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object tcpRouteId_ = ""; /** * * * <pre> * Required. Short name of the TcpRoute resource to be created. * </pre> * * <code>string tcp_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The tcpRouteId. */ @java.lang.Override public java.lang.String getTcpRouteId() { java.lang.Object ref = tcpRouteId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); tcpRouteId_ = s; return s; } } /** * * * <pre> * Required. Short name of the TcpRoute resource to be created. * </pre> * * <code>string tcp_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for tcpRouteId. */ @java.lang.Override public com.google.protobuf.ByteString getTcpRouteIdBytes() { java.lang.Object ref = tcpRouteId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); tcpRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TCP_ROUTE_FIELD_NUMBER = 3; private com.google.cloud.networkservices.v1.TcpRoute tcpRoute_; /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tcpRoute field is set. */ @java.lang.Override public boolean hasTcpRoute() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tcpRoute. */ @java.lang.Override public com.google.cloud.networkservices.v1.TcpRoute getTcpRoute() { return tcpRoute_ == null ? com.google.cloud.networkservices.v1.TcpRoute.getDefaultInstance() : tcpRoute_; } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.networkservices.v1.TcpRouteOrBuilder getTcpRouteOrBuilder() { return tcpRoute_ == null ? com.google.cloud.networkservices.v1.TcpRoute.getDefaultInstance() : tcpRoute_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tcpRouteId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, tcpRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getTcpRoute()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tcpRouteId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, tcpRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getTcpRoute()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.networkservices.v1.CreateTcpRouteRequest)) { return super.equals(obj); } com.google.cloud.networkservices.v1.CreateTcpRouteRequest other = (com.google.cloud.networkservices.v1.CreateTcpRouteRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getTcpRouteId().equals(other.getTcpRouteId())) return false; if (hasTcpRoute() != other.hasTcpRoute()) return false; if (hasTcpRoute()) { if (!getTcpRoute().equals(other.getTcpRoute())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + TCP_ROUTE_ID_FIELD_NUMBER; hash = (53 * hash) + getTcpRouteId().hashCode(); if (hasTcpRoute()) { hash = (37 * hash) + TCP_ROUTE_FIELD_NUMBER; hash = (53 * hash) + getTcpRoute().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.networkservices.v1.CreateTcpRouteRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request used by the TcpRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateTcpRouteRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.networkservices.v1.CreateTcpRouteRequest) com.google.cloud.networkservices.v1.CreateTcpRouteRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.TcpRouteProto .internal_static_google_cloud_networkservices_v1_CreateTcpRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.TcpRouteProto .internal_static_google_cloud_networkservices_v1_CreateTcpRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateTcpRouteRequest.class, com.google.cloud.networkservices.v1.CreateTcpRouteRequest.Builder.class); } // Construct using com.google.cloud.networkservices.v1.CreateTcpRouteRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTcpRouteFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; tcpRouteId_ = ""; tcpRoute_ = null; if (tcpRouteBuilder_ != null) { tcpRouteBuilder_.dispose(); tcpRouteBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.networkservices.v1.TcpRouteProto .internal_static_google_cloud_networkservices_v1_CreateTcpRouteRequest_descriptor; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTcpRouteRequest getDefaultInstanceForType() { return com.google.cloud.networkservices.v1.CreateTcpRouteRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTcpRouteRequest build() { com.google.cloud.networkservices.v1.CreateTcpRouteRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTcpRouteRequest buildPartial() { com.google.cloud.networkservices.v1.CreateTcpRouteRequest result = new com.google.cloud.networkservices.v1.CreateTcpRouteRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.networkservices.v1.CreateTcpRouteRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.tcpRouteId_ = tcpRouteId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.tcpRoute_ = tcpRouteBuilder_ == null ? tcpRoute_ : tcpRouteBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.networkservices.v1.CreateTcpRouteRequest) { return mergeFrom((com.google.cloud.networkservices.v1.CreateTcpRouteRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.networkservices.v1.CreateTcpRouteRequest other) { if (other == com.google.cloud.networkservices.v1.CreateTcpRouteRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getTcpRouteId().isEmpty()) { tcpRouteId_ = other.tcpRouteId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasTcpRoute()) { mergeTcpRoute(other.getTcpRoute()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { tcpRouteId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getTcpRouteFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the TcpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource of the TcpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource of the TcpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the TcpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the TcpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object tcpRouteId_ = ""; /** * * * <pre> * Required. Short name of the TcpRoute resource to be created. * </pre> * * <code>string tcp_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The tcpRouteId. */ public java.lang.String getTcpRouteId() { java.lang.Object ref = tcpRouteId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); tcpRouteId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Short name of the TcpRoute resource to be created. * </pre> * * <code>string tcp_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for tcpRouteId. */ public com.google.protobuf.ByteString getTcpRouteIdBytes() { java.lang.Object ref = tcpRouteId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); tcpRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Short name of the TcpRoute resource to be created. * </pre> * * <code>string tcp_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The tcpRouteId to set. * @return This builder for chaining. */ public Builder setTcpRouteId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } tcpRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Short name of the TcpRoute resource to be created. * </pre> * * <code>string tcp_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearTcpRouteId() { tcpRouteId_ = getDefaultInstance().getTcpRouteId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. Short name of the TcpRoute resource to be created. * </pre> * * <code>string tcp_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for tcpRouteId to set. * @return This builder for chaining. */ public Builder setTcpRouteIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); tcpRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.networkservices.v1.TcpRoute tcpRoute_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.TcpRoute, com.google.cloud.networkservices.v1.TcpRoute.Builder, com.google.cloud.networkservices.v1.TcpRouteOrBuilder> tcpRouteBuilder_; /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tcpRoute field is set. */ public boolean hasTcpRoute() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tcpRoute. */ public com.google.cloud.networkservices.v1.TcpRoute getTcpRoute() { if (tcpRouteBuilder_ == null) { return tcpRoute_ == null ? com.google.cloud.networkservices.v1.TcpRoute.getDefaultInstance() : tcpRoute_; } else { return tcpRouteBuilder_.getMessage(); } } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTcpRoute(com.google.cloud.networkservices.v1.TcpRoute value) { if (tcpRouteBuilder_ == null) { if (value == null) { throw new NullPointerException(); } tcpRoute_ = value; } else { tcpRouteBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTcpRoute( com.google.cloud.networkservices.v1.TcpRoute.Builder builderForValue) { if (tcpRouteBuilder_ == null) { tcpRoute_ = builderForValue.build(); } else { tcpRouteBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeTcpRoute(com.google.cloud.networkservices.v1.TcpRoute value) { if (tcpRouteBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && tcpRoute_ != null && tcpRoute_ != com.google.cloud.networkservices.v1.TcpRoute.getDefaultInstance()) { getTcpRouteBuilder().mergeFrom(value); } else { tcpRoute_ = value; } } else { tcpRouteBuilder_.mergeFrom(value); } if (tcpRoute_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearTcpRoute() { bitField0_ = (bitField0_ & ~0x00000004); tcpRoute_ = null; if (tcpRouteBuilder_ != null) { tcpRouteBuilder_.dispose(); tcpRouteBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.TcpRoute.Builder getTcpRouteBuilder() { bitField0_ |= 0x00000004; onChanged(); return getTcpRouteFieldBuilder().getBuilder(); } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.TcpRouteOrBuilder getTcpRouteOrBuilder() { if (tcpRouteBuilder_ != null) { return tcpRouteBuilder_.getMessageOrBuilder(); } else { return tcpRoute_ == null ? com.google.cloud.networkservices.v1.TcpRoute.getDefaultInstance() : tcpRoute_; } } /** * * * <pre> * Required. TcpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TcpRoute tcp_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.TcpRoute, com.google.cloud.networkservices.v1.TcpRoute.Builder, com.google.cloud.networkservices.v1.TcpRouteOrBuilder> getTcpRouteFieldBuilder() { if (tcpRouteBuilder_ == null) { tcpRouteBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.TcpRoute, com.google.cloud.networkservices.v1.TcpRoute.Builder, com.google.cloud.networkservices.v1.TcpRouteOrBuilder>( getTcpRoute(), getParentForChildren(), isClean()); tcpRoute_ = null; } return tcpRouteBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.networkservices.v1.CreateTcpRouteRequest) } // @@protoc_insertion_point(class_scope:google.cloud.networkservices.v1.CreateTcpRouteRequest) private static final com.google.cloud.networkservices.v1.CreateTcpRouteRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.networkservices.v1.CreateTcpRouteRequest(); } public static com.google.cloud.networkservices.v1.CreateTcpRouteRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateTcpRouteRequest> PARSER = new com.google.protobuf.AbstractParser<CreateTcpRouteRequest>() { @java.lang.Override public CreateTcpRouteRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<CreateTcpRouteRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateTcpRouteRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTcpRouteRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,309
java-networkservices/proto-google-cloud-networkservices-v1/src/main/java/com/google/cloud/networkservices/v1/CreateTlsRouteRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/networkservices/v1/tls_route.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.networkservices.v1; /** * * * <pre> * Request used by the TlsRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateTlsRouteRequest} */ public final class CreateTlsRouteRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.networkservices.v1.CreateTlsRouteRequest) CreateTlsRouteRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateTlsRouteRequest.newBuilder() to construct. private CreateTlsRouteRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateTlsRouteRequest() { parent_ = ""; tlsRouteId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateTlsRouteRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.TlsRouteProto .internal_static_google_cloud_networkservices_v1_CreateTlsRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.TlsRouteProto .internal_static_google_cloud_networkservices_v1_CreateTlsRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateTlsRouteRequest.class, com.google.cloud.networkservices.v1.CreateTlsRouteRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the TlsRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource of the TlsRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TLS_ROUTE_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object tlsRouteId_ = ""; /** * * * <pre> * Required. Short name of the TlsRoute resource to be created. * </pre> * * <code>string tls_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The tlsRouteId. */ @java.lang.Override public java.lang.String getTlsRouteId() { java.lang.Object ref = tlsRouteId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); tlsRouteId_ = s; return s; } } /** * * * <pre> * Required. Short name of the TlsRoute resource to be created. * </pre> * * <code>string tls_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for tlsRouteId. */ @java.lang.Override public com.google.protobuf.ByteString getTlsRouteIdBytes() { java.lang.Object ref = tlsRouteId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); tlsRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TLS_ROUTE_FIELD_NUMBER = 3; private com.google.cloud.networkservices.v1.TlsRoute tlsRoute_; /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tlsRoute field is set. */ @java.lang.Override public boolean hasTlsRoute() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tlsRoute. */ @java.lang.Override public com.google.cloud.networkservices.v1.TlsRoute getTlsRoute() { return tlsRoute_ == null ? com.google.cloud.networkservices.v1.TlsRoute.getDefaultInstance() : tlsRoute_; } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.networkservices.v1.TlsRouteOrBuilder getTlsRouteOrBuilder() { return tlsRoute_ == null ? com.google.cloud.networkservices.v1.TlsRoute.getDefaultInstance() : tlsRoute_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tlsRouteId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, tlsRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getTlsRoute()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tlsRouteId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, tlsRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getTlsRoute()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.networkservices.v1.CreateTlsRouteRequest)) { return super.equals(obj); } com.google.cloud.networkservices.v1.CreateTlsRouteRequest other = (com.google.cloud.networkservices.v1.CreateTlsRouteRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getTlsRouteId().equals(other.getTlsRouteId())) return false; if (hasTlsRoute() != other.hasTlsRoute()) return false; if (hasTlsRoute()) { if (!getTlsRoute().equals(other.getTlsRoute())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + TLS_ROUTE_ID_FIELD_NUMBER; hash = (53 * hash) + getTlsRouteId().hashCode(); if (hasTlsRoute()) { hash = (37 * hash) + TLS_ROUTE_FIELD_NUMBER; hash = (53 * hash) + getTlsRoute().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.networkservices.v1.CreateTlsRouteRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request used by the TlsRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateTlsRouteRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.networkservices.v1.CreateTlsRouteRequest) com.google.cloud.networkservices.v1.CreateTlsRouteRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.TlsRouteProto .internal_static_google_cloud_networkservices_v1_CreateTlsRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.TlsRouteProto .internal_static_google_cloud_networkservices_v1_CreateTlsRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateTlsRouteRequest.class, com.google.cloud.networkservices.v1.CreateTlsRouteRequest.Builder.class); } // Construct using com.google.cloud.networkservices.v1.CreateTlsRouteRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTlsRouteFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; tlsRouteId_ = ""; tlsRoute_ = null; if (tlsRouteBuilder_ != null) { tlsRouteBuilder_.dispose(); tlsRouteBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.networkservices.v1.TlsRouteProto .internal_static_google_cloud_networkservices_v1_CreateTlsRouteRequest_descriptor; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTlsRouteRequest getDefaultInstanceForType() { return com.google.cloud.networkservices.v1.CreateTlsRouteRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTlsRouteRequest build() { com.google.cloud.networkservices.v1.CreateTlsRouteRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTlsRouteRequest buildPartial() { com.google.cloud.networkservices.v1.CreateTlsRouteRequest result = new com.google.cloud.networkservices.v1.CreateTlsRouteRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.networkservices.v1.CreateTlsRouteRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.tlsRouteId_ = tlsRouteId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.tlsRoute_ = tlsRouteBuilder_ == null ? tlsRoute_ : tlsRouteBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.networkservices.v1.CreateTlsRouteRequest) { return mergeFrom((com.google.cloud.networkservices.v1.CreateTlsRouteRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.networkservices.v1.CreateTlsRouteRequest other) { if (other == com.google.cloud.networkservices.v1.CreateTlsRouteRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getTlsRouteId().isEmpty()) { tlsRouteId_ = other.tlsRouteId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasTlsRoute()) { mergeTlsRoute(other.getTlsRoute()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { tlsRouteId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getTlsRouteFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the TlsRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource of the TlsRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource of the TlsRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the TlsRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the TlsRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object tlsRouteId_ = ""; /** * * * <pre> * Required. Short name of the TlsRoute resource to be created. * </pre> * * <code>string tls_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The tlsRouteId. */ public java.lang.String getTlsRouteId() { java.lang.Object ref = tlsRouteId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); tlsRouteId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Short name of the TlsRoute resource to be created. * </pre> * * <code>string tls_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for tlsRouteId. */ public com.google.protobuf.ByteString getTlsRouteIdBytes() { java.lang.Object ref = tlsRouteId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); tlsRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Short name of the TlsRoute resource to be created. * </pre> * * <code>string tls_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The tlsRouteId to set. * @return This builder for chaining. */ public Builder setTlsRouteId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } tlsRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Short name of the TlsRoute resource to be created. * </pre> * * <code>string tls_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearTlsRouteId() { tlsRouteId_ = getDefaultInstance().getTlsRouteId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. Short name of the TlsRoute resource to be created. * </pre> * * <code>string tls_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for tlsRouteId to set. * @return This builder for chaining. */ public Builder setTlsRouteIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); tlsRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.networkservices.v1.TlsRoute tlsRoute_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.TlsRoute, com.google.cloud.networkservices.v1.TlsRoute.Builder, com.google.cloud.networkservices.v1.TlsRouteOrBuilder> tlsRouteBuilder_; /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tlsRoute field is set. */ public boolean hasTlsRoute() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tlsRoute. */ public com.google.cloud.networkservices.v1.TlsRoute getTlsRoute() { if (tlsRouteBuilder_ == null) { return tlsRoute_ == null ? com.google.cloud.networkservices.v1.TlsRoute.getDefaultInstance() : tlsRoute_; } else { return tlsRouteBuilder_.getMessage(); } } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTlsRoute(com.google.cloud.networkservices.v1.TlsRoute value) { if (tlsRouteBuilder_ == null) { if (value == null) { throw new NullPointerException(); } tlsRoute_ = value; } else { tlsRouteBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTlsRoute( com.google.cloud.networkservices.v1.TlsRoute.Builder builderForValue) { if (tlsRouteBuilder_ == null) { tlsRoute_ = builderForValue.build(); } else { tlsRouteBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeTlsRoute(com.google.cloud.networkservices.v1.TlsRoute value) { if (tlsRouteBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && tlsRoute_ != null && tlsRoute_ != com.google.cloud.networkservices.v1.TlsRoute.getDefaultInstance()) { getTlsRouteBuilder().mergeFrom(value); } else { tlsRoute_ = value; } } else { tlsRouteBuilder_.mergeFrom(value); } if (tlsRoute_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearTlsRoute() { bitField0_ = (bitField0_ & ~0x00000004); tlsRoute_ = null; if (tlsRouteBuilder_ != null) { tlsRouteBuilder_.dispose(); tlsRouteBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.TlsRoute.Builder getTlsRouteBuilder() { bitField0_ |= 0x00000004; onChanged(); return getTlsRouteFieldBuilder().getBuilder(); } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.TlsRouteOrBuilder getTlsRouteOrBuilder() { if (tlsRouteBuilder_ != null) { return tlsRouteBuilder_.getMessageOrBuilder(); } else { return tlsRoute_ == null ? com.google.cloud.networkservices.v1.TlsRoute.getDefaultInstance() : tlsRoute_; } } /** * * * <pre> * Required. TlsRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.TlsRoute tls_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.TlsRoute, com.google.cloud.networkservices.v1.TlsRoute.Builder, com.google.cloud.networkservices.v1.TlsRouteOrBuilder> getTlsRouteFieldBuilder() { if (tlsRouteBuilder_ == null) { tlsRouteBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.TlsRoute, com.google.cloud.networkservices.v1.TlsRoute.Builder, com.google.cloud.networkservices.v1.TlsRouteOrBuilder>( getTlsRoute(), getParentForChildren(), isClean()); tlsRoute_ = null; } return tlsRouteBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.networkservices.v1.CreateTlsRouteRequest) } // @@protoc_insertion_point(class_scope:google.cloud.networkservices.v1.CreateTlsRouteRequest) private static final com.google.cloud.networkservices.v1.CreateTlsRouteRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.networkservices.v1.CreateTlsRouteRequest(); } public static com.google.cloud.networkservices.v1.CreateTlsRouteRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateTlsRouteRequest> PARSER = new com.google.protobuf.AbstractParser<CreateTlsRouteRequest>() { @java.lang.Override public CreateTlsRouteRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<CreateTlsRouteRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateTlsRouteRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateTlsRouteRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/nosql
36,701
kvmain/src/main/java/com/sleepycat/je/util/DbBackup.java
/*- * Copyright (C) 2002, 2025, Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle NoSQL * Database made available at: * * http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle NoSQL Database for a copy of the license and * additional information. */ package com.sleepycat.je.util; import java.util.HashSet; import java.util.NavigableSet; import java.util.Set; import com.sleepycat.je.CheckpointConfig; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.DbInternal; import com.sleepycat.je.Environment; import com.sleepycat.je.EnvironmentFailureException; import com.sleepycat.je.EnvironmentStats; import com.sleepycat.je.cleaner.EraserAbortException; import com.sleepycat.je.cleaner.FileProtector; import com.sleepycat.je.cleaner.FileProtector.ProtectedActiveFileSet; import com.sleepycat.je.cleaner.FileProtector.ProtectedFileRange; import com.sleepycat.je.config.EnvironmentParams; import com.sleepycat.je.dbi.EnvironmentImpl; import com.sleepycat.je.log.FileManager; import com.sleepycat.je.log.LogEntryType; import com.sleepycat.je.log.ReplicationContext; import com.sleepycat.je.log.entry.EmptyLogEntry; import com.sleepycat.je.log.entry.LogEntry; import com.sleepycat.je.log.entry.SingleItemEntry; import com.sleepycat.je.rep.LogOverwriteException; import com.sleepycat.je.rep.impl.RepImpl; import com.sleepycat.je.rep.vlsn.VLSNIndex; import com.sleepycat.je.utilint.DbLsn; import com.sleepycat.je.utilint.TestHook; import com.sleepycat.je.utilint.TestHookExecute; /** * DbBackup is a helper class for stopping and restarting JE background * activity in an open environment in order to simplify backup operations. It * also lets the application create a backup which can support restoring the * environment to a specific point in time. * <p> * <b>Backing up without DbBackup</b> * <p> * Because JE has an append only log file architecture, it is always possible * to do a hot backup without the use of DbBackup by copying all log files * (.jdb files) to your archival location. As long as the log files are copied * in alphabetical order, (numerical in effect) <i>and</i> all log files are * copied, the environment can be successfully backed up without any need to * stop database operations or background activity. This means that your * backup operation must do a loop to check for the creation of new log files * before deciding that the backup is finished. For example: * <pre> * time files in activity * environment * * t0 000000001.jdb Backup starts copying file 1 * 000000003.jdb * 000000004.jdb * * t1 000000001.jdb JE log cleaner migrates portion of file 3 to newly * 000000004.jdb created file 5 and deletes file 3. Backup finishes * 000000005.jdb file 1, starts copying file 4. Backup MUST include * file 5 for a consistent backup! * * t2 000000001.jdb Backup finishes copying file 4, starts and * 000000004.jdb finishes file 5, has caught up. Backup ends. * 000000005.jdb *</pre> * <p> * In the example above, the backup operation must be sure to copy file 5, * which came into existence after the backup had started. If the backup * stopped operations at file 4, the backup set would include only file 1 and * 4, omitting file 3, which would be an inconsistent set. * <p> * Also note that log file 5 may not have filled up before it was copied to * archival storage. On the next backup, there might be a newer, larger version * of file 5, and that newer version should replace the older file 5 in archive * storage. * <p> * Using the approach above, as opposed to using DbBackup, will copy all files * including {@link EnvironmentStats#getReservedLogSize reserved files} as well * as {@link EnvironmentStats#getActiveLogSize active files}. A large number of * reserved files may be present in an HA Environment, and they are essentially * wasted space in a backup. Using DbBackup is strongly recommended for this * reason, as well as to reduce the complexity of file copying. * <p> * <b>Backing up with DbBackup</b> * <p> * DbBackup helps simplify application backup by defining the set of {@link * EnvironmentStats#getActiveLogSize active files} that must be copied for each * backup operation. If the environment directory has read/write protection, * the application must pass DbBackup an open, read/write environment handle. * <p> * When entering backup mode, JE determines the set of active files needed for * a consistent backup, and freezes all changes to those files. The application * can copy that defined set of files and finish operation without checking for * the ongoing creation of new files. Also, there will be no need to check for * a newer version of the last file on the next backup. * <p> * In the example above, if DbBackup was used at t0, the application would only * have to copy files 1, 3 and 4 to back up. On a subsequent backup, the * application could start its copying at file 5. There would be no need to * check for a newer version of file 4. * <p> * When it is important to minimize the time that it takes to recover using a * backup, a checkpoint should be performed immediately before calling {@link * #startBackup}. This will reduce recovery time when opening the environment * with the restored log files. A checkpoint is performed explicitly by * calling {@link Environment#checkpoint} using a config object for which * {@link CheckpointConfig#setForce setForce(true)} has been called. * <p> * <b>Performing simple/full backups</b> * <p> * The following examples shows how to perform a full backup. A checkpoint is * performed to minimize recovery time. * <pre class="code"> * void myBackup(Environment env, File destDir) { * DbBackup backupHelper = new DbBackup(env); * * // Optional: Do a checkpoint to reduce recovery time after a restore. * env.checkpoint(new CheckpointConfig().setForce(true)); * * // Start backup, find out what needs to be copied. * backupHelper.startBackup(); * try { * // Copy the necessary files to archival storage. * String[] filesToCopy = backupHelper.getLogFilesInBackupSet(); * myCopyFiles(env, backupHelper, filesToCopy, destDir); * } finally { * // Remember to exit backup mode, or the JE cleaner cannot delete * // log files and disk usage will grow without bounds. * backupHelper.endBackup(); * } * } * * void myCopyFiles( * Environment env, * DbBackup backupHelper, * String[] filesToCopy, * File destDir) { * * for (String fileName : filesToCopy) { * // Copy fileName to destDir. * // See {@link LogVerificationReadableByteChannel} and * // {@link LogVerificationInputStream}. * .... * * // Remove protection to allow file to be deleted in order to reclaim * // disk space. * backupHelper.removeFileProtection(fileName); * } * } * </pre> * When copying files to the backup directory, it is critical that each file is * verified before or during the copy. If a file is copied that is corrupt * (due to an earlier disk failure that went unnoticed, for example), the * backup will be invalid and provide a false sense of security. * <p> * The {@link LogVerificationInputStream example here} shows how to implement * the {@code myCopyFiles} method using {@link * LogVerificationInputStream}. A {@link LogVerificationReadableByteChannel} * could also be used for higher performance copying. A filter input stream is * used to verify the file efficiently as it is being read. If you choose to * use a script for copying files, the {@link DbVerifyLog} command line tool * can be used instead. * <p> * Assuming that the full backup copied files into an empty directory, to * restore you can simply copy these files back into another empty directory. * <p> * Always start with an empty directory as the destination for a full backup or * a restore, to ensure that no unused files are present. Unused files -- * perhaps the residual of an earlier environment or an earlier backup -- will * take up space, and they will never be deleted by the JE log cleaner. Also * note that such files will not be used by JE for calculating utilization and * will not appear in the {@link DbSpace} output. * <p> * <b>Performing incremental backups</b> * <p> * Incremental backups are used to reduce the number of files copied during * each backup. Compared to a full backup, there are two additional pieces of * information needed for an incremental backup: the number of the last file in * the previous backup, and a list of the active files in the environment * directory at the time of the current backup, i.e., the current snapshot. * Their purpose is explained below. * <p> * The number of the last file in the previous backup is used to avoid copying * files that are already present in the backup set. This file number must be * obtained before beginning the backup, either by checking the backup archive, * or getting this value from a stored location. For example, the last file * number could be written to a special file in the backup set at the time of a * backup, and then read from the special file before starting the next backup. * <p> * The list of files in the current snapshot, which should be obtained by * calling {@link #getLogFilesInSnapshot} (after calling {@link #startBackup}), * is used to avoid unused files after a restore, and may also be used to * reduce the size of the backup set. How to use this list is described below. * <p> * Some applications need the ability to restore to the point in time of any of * the incremental backups that were made in the past, and other applications * only need to restore to the point in time of the most recent backup. * Accordingly, the list of current files (that is made at the time of the * backup), should be used in one of two ways. * <ol> * <li>If you only need to restore to the point in time of the most recent * backup, then the list should be used to delete unused files from the * backup set. After copying all files during the backup, any file that is * <em>not</em> present in the list may then be deleted from the backup set. * This both reduces the size of the backup set, and ensures that unused * files will not be present in the backup set and therefore will not be * restored.</li> * <li>If you need to keep all log files from each backup so you can restore * to more than one point in time, then the list for each backup should be * saved with the backup file set so it can be used during a restore. During * the restore, only the files in the list should be copied, starting with an * empty destination directory. This ensures that unused files will not be * restored.</li> * </ol> * <p> * The following two examples shows how to perform an incremental backup. In * the first example, the list of current files is used to delete files from * the backup set that are no longer needed. * <pre class="code"> * void myBackup(Environment env, File destDir) { * * // Get the file number of the last file in the previous backup. * long lastFileInPrevBackup = ... * * DbBackup backupHelper = new DbBackup(env, lastFileInPrevBackup); * * // Optional: Do a checkpoint to reduce recovery time after a restore. * env.checkpoint(new CheckpointConfig().setForce(true)); * * // Start backup, find out what needs to be copied. * backupHelper.startBackup(); * try { * // Copy the necessary files to archival storage. * String[] filesToCopy = backupHelper.getLogFilesInBackupSet(); * myCopyFiles(env, backupHelper, filesToCopy, destDir); * * // Delete files that are no longer needed. * // WARNING: This should only be done after copying all new files. * String[] filesInSnapshot = backupHelper.getLogFilesInSnapshot(); * myDeleteUnusedFiles(destDir, filesInSnapshot); * * // Update knowledge of last file saved in the backup set. * lastFileInPrevBackup = backupHelper.getLastFileInBackupSet(); * // Save lastFileInPrevBackup persistently here ... * } finally { * // Remember to exit backup mode, or the JE cleaner cannot delete * // log files and disk usage will grow without bounds. * backupHelper.endBackup(); * } * } * * void myDeleteUnusedFiles(File destDir, String[] filesInSnapshot) { * // For each file in destDir that is NOT in filesInSnapshot, it should * // be deleted from destDir to save disk space in the backup set, and to * // ensure that unused files will not be restored. * } * * See myCopyFiles further above. * </pre> * <p> * When performing backups as shown in the first example above, to restore you * can simply copy all files from the backup set into an empty directory. * <p> * In the second example below, the list of current files is saved with the * backup set so it can be used during a restore. The backup set will * effectively hold multiple backups that can be used to restore to different * points in time. * <pre class="code"> * void myBackup(Environment env, File destDir) { * * // Get the file number of the last file in the previous backup. * long lastFileInPrevBackup = ... * * DbBackup backupHelper = new DbBackup(env, lastFileInPrevBackup); * * // Optional: Do a checkpoint to reduce recovery time after a restore. * env.checkpoint(new CheckpointConfig().setForce(true)); * * // Start backup, find out what needs to be copied. * backupHelper.startBackup(); * try { * // Copy the necessary files to archival storage. * String[] filesToCopy = backupHelper.getLogFilesInBackupSet(); * myCopyFiles(env, backupHelper, filesToCopy, destDir); * * // Save current list of files with backup data set. * String[] filesInSnapshot = backupHelper.getLogFilesInSnapshot(); * // Save filesInSnapshot persistently here ... * * // Update knowledge of last file saved in the backup set. * lastFileInPrevBackup = backupHelper.getLastFileInBackupSet(); * // Save lastFileInPrevBackup persistently here ... * } finally { * // Remember to exit backup mode, or the JE cleaner cannot delete * // log files and disk usage will grow without bounds. * backupHelper.endBackup(); * } * } * * See myCopyFiles further above. * </pre> * <p> * When performing backups as shown in the second example above, to restore you * must choose one of the file lists that was saved. You may choose the list * written by the most recent backup, or a list written by an earlier backup. * To restore, the files in the list should be copied into an empty destination * directory. * <p> * <b><a href="restore">Restoring from a backup</a></b> * <p> * As described in the sections above, the restore procedure is to copy the * files from a backup set into an empty directory. Depending on the type of * backup that was performed (see above), either all files from the backup set * are copied, or only the files on a list that was created during the backup. * <p> * There is one additional consideration when performing a restore, under the * following condition: * <ul> * <li>Incremental backups are used, AND * <ul> * <li>the backup was created using DbBackup with JE 6.2 or earlier, * OR</li> * <li>the backup was created in a read-only JE environment.</li> * </ul> * </li> * </ul> * <p> * If the above condition holds, after copying the files an additional step is * needed. To enable the creation of future incremental backups using the * restored files, the {@link * com.sleepycat.je.EnvironmentConfig#ENV_RECOVERY_FORCE_NEW_FILE} parameter * should be set to true when opening the JE Environment for the first time * after the restore. When this parameter is set to true, the last .jdb file * restored will not be modified when opening the Environment, and the next * .jdb file will be created and will become the end-of-log file. * <p> * WARNING: When the above special condition is true and this property is * <em>not</em> set to true when opening the environment for the first time * after a restore, then the backup set that was restored may not be used as * the basis for future incremental backups. If a future incremental backup * were performed based on this backup set, it would be incomplete and data * would be lost if that incremental backup were restored. * <p> * When JE 6.3 or later is used to create the backup, and the backup is created * in a read-write environment (the usual case), this extra step is * unnecessary. In this case, {@link #startBackup} will have added an * "immutable file" marker to the last file in the backup and this will prevent * that file from being modified, just as if the * {@code ENV_RECOVERY_FORCE_NEW_FILE} parameter were set to true. */ public class DbBackup { private final EnvironmentImpl envImpl; private final boolean envIsReadOnly; private final long firstFileInBackup; private long lastFileInBackup = -1; private boolean backupStarted; private boolean networkRestore; private int networkRestoreClientId; private ProtectedActiveFileSet protectedFileSet; private NavigableSet<Long> snapshotFiles; /* Status presents whether this back up is invalid because of roll back. */ private boolean invalid; /* The rollback start file number. */ private long rollbackStartedFileNumber; /* For unit tests. */ private TestHook<?> testEndBackupHook; private TestHook<?> testStartWindowHook; /** * Creates a DbBackup helper for a full backup. * * <p>This is equivalent to using {@link #DbBackup(Environment,long)} and * passing {@code -1} for the {@code lastFileInPrevBackup} parameter.</p> * * @param env with an open, valid environment handle. If the environment * directory has read/write permissions, the environment handle must be * configured for read/write. * * @throws IllegalArgumentException if the environment directory has * read/write permissions, but the environment handle is not configured for * read/write. */ public DbBackup(Environment env) throws DatabaseException { this(env, -1); } /** * Creates a DbBackup helper for an incremental backup. * * @param env with an open, valid environment handle. If the environment * directory has read/write permissions, the environment handle must be * configured for read/write. * * @param lastFileInPrevBackup the last file in the previous backup set * when performing an incremental backup, or {@code -1} to perform a full * backup. The first file in this backup set will be the file following * {@code lastFileInPrevBackup}. * * @throws EnvironmentFailureException if an unexpected, internal or * environment-wide failure occurs. * * @throws IllegalArgumentException if the environment directory has * read/write permissions, but the environment handle is not configured for * read/write. */ public DbBackup(Environment env, long lastFileInPrevBackup) { this(env, DbInternal.getNonNullEnvImpl(env), lastFileInPrevBackup); } /** * @hidden * For internal use only. */ public DbBackup(EnvironmentImpl envImpl) { this(null, envImpl, -1); } /** * This is the true body of the DbBackup constructor. The env param may be * null when this class is used internally. */ private DbBackup(Environment env, EnvironmentImpl envImpl, long lastFileInPrevBackup) { /* Check that the Environment is open. */ if (env != null) { DbInternal.checkOpen(env); } this.envImpl = envImpl; /* * If the environment is writable, we need a r/w environment handle * in order to flip the file. */ envIsReadOnly = envImpl.getFileManager().checkEnvHomePermissions(true); if ((!envIsReadOnly) && envImpl.isReadOnly()) { throw new IllegalArgumentException ("Environment handle may not be read-only when directory " + "is read-write"); } firstFileInBackup = lastFileInPrevBackup + 1; } /** * Start backup mode in order to determine the definitive backup set needed * at this point in time. * * <p>This method determines the last file in the backup set, which is the * last log file in the environment at this point in time. Following this * method call, all new data will be written to other, new log files. In * other words, the last file in the backup set will not be modified after * this method returns.</p> * * <p><em>WARNING:</em> After calling this method, deletion of log files in * the backup set by the JE log cleaner will be disabled until {@link * #endBackup()} is called. To prevent unbounded growth of disk usage, be * sure to call {@link #endBackup()} to re-enable log file deletion. * Additionally, the Environment can't be closed until endBackup() is * called. * </p> * * @throws com.sleepycat.je.rep.LogOverwriteException if a replication * operation is overwriting log files. The backup can not proceed because * files may be invalid. The backup may be attempted at a later time. * * @throws EnvironmentFailureException if an unexpected, internal or * environment-wide failure occurs. * * @throws IllegalStateException if a backup is already in progress * * <!-- * @throws EraserAbortException if we can't abort erasure of a target * file within {@link EnvironmentParams#ERASE_ABORT_TIMEOUT}. The * timeout is long, so this should not happen unless the eraser thread * is wedged or starved. (This exception is undocumented because erasure * is not an exposed feature.) * --> */ public synchronized void startBackup() throws DatabaseException { if (backupStarted) { throw new IllegalStateException("startBackup was already called"); } /* Throw a LogOverwriteException if the Environment is rolling back. */ if (!envImpl.addDbBackup(this)) { throw new LogOverwriteException( "A replication operation is overwriting log files. The " + "backup can not proceed because files may be invalid. The " + "backup may be attempted at a later time."); } final FileProtector fileProtector = envImpl.getFileProtector(); /* * For a network restore we use a different backup name/id and also * select two reserved files, giving preference to recent files * containing VLSNs. The reserved files have two purposes: * 1. The rep stream portion of the log (covered by the VLSNIndex) must * not be allowed to become empty on the restored node. If there are * no active files in the rep stream then we must include at least * the most recent reserved file that is part of the rep stream. * Otherwise the VLSNIndex will become empty when it is truncated on * the restored node during recovery [KVSTORE-467]. * 2. Sending some reserved files is safeguard against other edge * conditions that might prevent the restored node from performing * recovery or functioning as a master. * In a future release this approach may be improved by additionally * copying all reserved files to the restored node, but only after it * has recovered using the active files [#25783]. */ final long backupId = networkRestore ? networkRestoreClientId : envImpl.getNodeSequence().getNextBackupId(); final String backupName = (networkRestore ? FileProtector.NETWORK_RESTORE_NAME : FileProtector.BACKUP_NAME) + "-" + backupId; final int nReservedFiles = networkRestore ? 2 : 0; /* * Protect all files from deletion momentarily, while determining the * last file, aborting erasure and protecting the active files. */ final ProtectedFileRange allFilesProtected = fileProtector.protectFileRange( backupName + FileProtector.TEMP_SUFFIX, 0); try { /* * In rare cases it is possible for the active log files to not * contain the last sync point, or any replicated logs at all. If * that happens then restoring from the backup will fail because it * would require truncating the only possible matchpoint form the * VLSNIndex. As such find the file containing the matchpoint and * make sure it is part of the backup set. * See KVSTORE-1931 */ long matchpointFile = DbLsn.NULL_LSN; if (envImpl.isReplicated()) { final RepImpl repImpl = (RepImpl) envImpl; final VLSNIndex vlsnIndex = repImpl.getVLSNIndex(); long lastSync = vlsnIndex.getRange().getLastSync(); if (lastSync != DbLsn.NULL_LSN) { matchpointFile = vlsnIndex.getLTEFileNumber(lastSync); } } /* * Abort erasure of all files while all files are protected, so * none of the files we select for the backup are in danger of * being erased. */ envImpl.getDataEraser().abortErase(allFilesProtected); /* * Protect active files from deletion prior to the file flip. This * includes files prior to firstFileInBackup, in order to get a * snapshot of all active files. New files (following those in the * final backup set) do not need protection, since the backup set * does not include them. */ protectedFileSet = fileProtector.protectActiveFiles( backupName, nReservedFiles, false /*protectNewFiles*/, matchpointFile); if (envIsReadOnly) { /* * All files are currently immutable, so the backup list is the * current set of files. However, we can't add a marker to the * last file in list, and therefore it will not be immutable * after being restored to a read-write directory (unless the * user sets ENV_RECOVERY_FORCE_NEW_FILE after restoring). */ lastFileInBackup = envImpl.getFileManager().getLastFileNum(); } else { /* * Flip the log so that all files in the backup list are * immutable. But first, write an "immutable file" marker in * the last file in the backup, so it cannot be modified after * it is restored. Recovery enforces this rule. */ final LogEntry marker = new SingleItemEntry<>( LogEntryType.LOG_IMMUTABLE_FILE, new EmptyLogEntry()); final long markerLsn = envImpl.getLogManager().log( marker, ReplicationContext.NO_REPLICATE); envImpl.forceLogFileFlip(); lastFileInBackup = DbLsn.getFileNumber(markerLsn); } assert TestHookExecute.doHookIfSet(testStartWindowHook); /* * Protect files following those initially protected up to and * including lastFileInBackup. See addFinalBackupFiles for details. */ protectedFileSet.addFinalBackupFiles(lastFileInBackup); } finally { fileProtector.removeFileProtection(allFilesProtected); } /* At this point, endBackup must be called to undo file protection. */ backupStarted = true; /* Files after lastFileInBackup do not need protection. */ protectedFileSet.truncateTail(lastFileInBackup); /* Snapshot the complete backup file set. */ snapshotFiles = protectedFileSet.getProtectedFiles(); /* * Now that we have the snapshot, files before firstFileInBackup do not * need protection. */ protectedFileSet.truncateHead(firstFileInBackup); } /** * End backup mode, thereby re-enabling normal deletion of log files by the * JE log cleaner. * * @throws com.sleepycat.je.rep.LogOverwriteException if a replication * operation has overwritten log files. Any copied files should be * considered invalid and discarded. The backup may be attempted at a * later time. * * @throws com.sleepycat.je.EnvironmentFailureException if an unexpected, * internal or environment-wide failure occurs. * * @throws IllegalStateException if a backup has not been started. */ public synchronized void endBackup() { checkBackupStarted(); backupStarted = false; assert TestHookExecute.doHookIfSet(testEndBackupHook); envImpl.getFileProtector().removeFileProtection(protectedFileSet); envImpl.removeDbBackup(this); /* If this back up is invalid, throw a LogOverwriteException. */ if (invalid) { invalid = false; throw new LogOverwriteException( "A replication operation has overwritten log files from " + "file " + rollbackStartedFileNumber + ". Any copied files " + "should be considered invalid and discarded. The backup " + "may be attempted at a later time."); } } /** * Can only be called in backup mode, after startBackup() has been called. * * @return the file number of the last file in the current backup set. * Save this value to reduce the number of files that must be copied at * the next backup session. * * @throws IllegalStateException if a backup has not been started. */ public synchronized long getLastFileInBackupSet() { checkBackupStarted(); return lastFileInBackup; } /** * Get the minimum list of files that must be copied for this backup. When * performing an incremental backup, this consists of the set of active * files that are greater than the last file copied in the previous backup * session. When performing a full backup, this consists of the set of all * active files. Can only be called in backup mode, after startBackup() has * been called. * * <p>The file numbers returned are in the range from the constructor * parameter {@code lastFileInPrevBackup + 1} to the last log file at the * time that {@link #startBackup} was called.</p> * * @return the names of all files to be copied, sorted in alphabetical * order. The return values are generally simple file names, not full * paths. * * @throws EnvironmentFailureException if an unexpected, internal or * environment-wide failure occurs. * * @throws IllegalStateException if a backup has not been started. */ public synchronized String[] getLogFilesInBackupSet() { checkBackupStarted(); return getFileNames(snapshotFiles.tailSet(firstFileInBackup, true)); } /** * Equivalent to {@link #getLogFilesInBackupSet} but returns file numbers. * Intended for testing. */ public synchronized Set<Long> getFileNumbersInBackupSet() { checkBackupStarted(); return new HashSet<>(snapshotFiles); } /** * Get the list of all active files that are needed for the environment at * the point of time when backup mode started, i.e., the current snapshot. * Can only be called in backup mode, after startBackup() has been called. * * <p>When performing an incremental backup, this method is called to * determine the files that would needed for a restore. As described in * the examples at the top of this class, this list can be used to avoid * unused files after a restore, and may also be used to reduce the size of * the backup set.</p> * * <p>When performing a full backup this method is normally not needed, * since in that case it returns the same set of files that is returned by * {@link #getLogFilesInBackupSet()}.</p> * * @return the names of all files in the snapshot, sorted in alphabetical * order. The return values are generally simple file names, not full * paths. * * @throws EnvironmentFailureException if an unexpected, internal or * environment-wide failure occurs. * * @throws IllegalStateException if a backup has not been started. */ public synchronized String[] getLogFilesInSnapshot() { checkBackupStarted(); return getFileNames(snapshotFiles); } private String[] getFileNames(NavigableSet<Long> fileSet) { final FileManager fileManager = envImpl.getFileManager(); final String[] names = new String[fileSet.size()]; int i = 0; for (Long file : fileSet) { names[i] = fileManager.getPartialFileName(file); i += 1; } return names; } /** * Removes protection for a file in the backup set. This method should be * called after copying a file, so that it may be deleted to avoid * exceeding disk usage limits. * * @param fileName a file name that has already been copied, in the format * returned by {@link #getLogFilesInBackupSet} . * * @since 7.5 */ public synchronized void removeFileProtection(String fileName) { checkBackupStarted(); protectedFileSet.removeFile( envImpl.getFileManager().getNumFromName(fileName)); } private void checkBackupStarted() { if (!backupStarted) { throw new IllegalStateException("startBackup was not called"); } } /** * For internal use only. * @hidden * Returns true if a backup has been started and is in progress. */ public synchronized boolean backupIsOpen() { return backupStarted; } /** * For internal use only. * @hidden * * Invalidate this backup if replication overwrites the log. */ public void invalidate(long fileNumber) { invalid = true; this.rollbackStartedFileNumber = fileNumber; } /** * For internal use only. * @hidden * * Marks this backup as a network restore. Causes the protected file set * name/id to be set specially, and two reserved files to be included. * See {@link #startBackup()}. * * Another approach (for future consideration) is to factor out the part * of DbBackup that is needed by network restore into utility methods, * so that special code for network restore can be removed from DbBackup. * The shared portion should be just the startBackup code. */ public void setNetworkRestore(int clientId) { networkRestore = true; networkRestoreClientId = clientId; } /** * For internal use only. * @hidden * * A test entry point used to simulate the environment is now rolling back, * and this TestHook would invalidate the in progress DbBackups. */ public void setEndBackupHook(TestHook<?> testHook) { this.testEndBackupHook = testHook; } /** * For internal use only. * @hidden * * A test entry point in the startBackup window between flipping the file * and getting the list of active files. */ public void setStartWindowHook(TestHook<?> testHook) { this.testStartWindowHook = testHook; } }
google/sagetv
36,397
third_party/MetadataExtractor/java/sage/media/exif/metadata/exif/ExifReader.java
/* * Early versions of this class were inspired by Jhead, a C program for extracting and * manipulating the Exif data within files written by Matthias Wandel. * http://www.sentex.net/~mwandel/jhead/ * * Jhead is public domain software - that is, you can do whatever you want * with it, and include it software that is licensed under the GNU or the * BSD license, or whatever other licence you choose, including proprietary * closed source licenses. Similarly, I release this Java version under the * same license, though I do ask that you leave this header in tact. * * If you make modifications to this code that you think would benefit the * wider community, please send me a copy and I'll post it on my site. Unlike * Jhead, this code (as it stands) only supports reading of Exif data - no * manipulation. * * If you make use of this code, I'd appreciate hearing about it. * drew.noakes@drewnoakes.com * Latest version of this software kept at * http://drewnoakes.com/ * * Created on 28 April 2002, 23:54 * Modified 04 Aug 2002 * - Renamed constants to be inline with changes to ExifTagValues interface * - Substituted usage of JDK 1.4 features (java.nio package) * Modified 29 Oct 2002 (v1.2) * - Proper traversing of Exif file structure and complete refactor & tidy of * the codebase (a few unnoticed bugs removed) * - Reads makernote data for 6 families of camera (5 makes) * - Tags now stored in directories... use the IFD_* constants to refer to the * image file directory you require (Exif, Interop, GPS and Makernote*) -- * this avoids collisions where two tags share the same code * - Takes componentCount of unknown tags into account * - Now understands GPS tags (thanks to Colin Briton for his help with this) * - Some other bug fixes, pointed out by users around the world. Thanks! * Modified 27 Nov 2002 (v2.0) * - Renamed to ExifReader * - Moved to new package sage.media.exif.metadata.exif * Modified since, however changes have not been logged. See release notes for * library-wide modifications. */ package sage.media.exif.metadata.exif; import java.io.File; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import sage.media.exif.imaging.jpeg.JpegProcessingException; import sage.media.exif.imaging.jpeg.JpegSegmentData; import sage.media.exif.imaging.jpeg.JpegSegmentReader; import sage.media.exif.lang.Rational; import sage.media.exif.metadata.Directory; import sage.media.exif.metadata.Metadata; import sage.media.exif.metadata.MetadataException; import sage.media.exif.metadata.MetadataReader; /** * Decodes Exif binary data, populating a <code>Metadata</code> object with * tag values in <code>ExifDirectory</code>, <code>GpsDirectory</code> and * one of the many camera makernote directories. * * @author Drew Noakes http://drewnoakes.com */ public class ExifReader implements MetadataReader { /** * The number of bytes used per format descriptor. */ private static final int[] BYTES_PER_FORMAT = { 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8 }; /** * The number of formats known. */ private static final int MAX_FORMAT_CODE = 12; // Format types // Note: Cannot use the DataFormat enumeration in the case statement that // uses these tags. // Is there a better way? private static final int FMT_BYTE = 1; private static final int FMT_STRING = 2; private static final int FMT_USHORT = 3; private static final int FMT_ULONG = 4; private static final int FMT_URATIONAL = 5; private static final int FMT_SBYTE = 6; private static final int FMT_UNDEFINED = 7; private static final int FMT_SSHORT = 8; private static final int FMT_SLONG = 9; private static final int FMT_SRATIONAL = 10; private static final int FMT_SINGLE = 11; private static final int FMT_DOUBLE = 12; public static final int TAG_EXIF_OFFSET = 0x8769; public static final int TAG_INTEROP_OFFSET = 0xA005; public static final int TAG_GPS_INFO_OFFSET = 0x8825; public static final int TAG_MAKER_NOTE = 0x927C; public static final int TIFF_HEADER_START_OFFSET = 6; /** * The Exif segment as an array of bytes. */ private final byte[] _data; /** * Represents the native byte ordering used in the JPEG segment. If true, * then we're using Motorolla ordering (Big endian), else we're using Intel * ordering (Little endian). */ private boolean _isMotorollaByteOrder; /** * Bean instance to store information about the image and * camera/scanner/capture device. */ private Metadata _metadata; /** * The Exif directory used (loaded lazily) */ private ExifDirectory _exifDirectory = null; /** * Creates an ExifReader for a JpegSegmentData object. * * @param segmentData * @deprecated Not all files will be Jpegs! This overload doesn't offer much * convenience to the caller. */ public ExifReader(JpegSegmentData segmentData) { // TODO consider removing this constructor and requiring callers to pass // a byte[] or other means to read the exif segment in isolation... not // all files will be Jpegs! this(segmentData.getSegment(JpegSegmentReader.SEGMENT_APP1)); } /** * Creates an ExifReader for a Jpeg jpegFile. * * @param jpegFile * @throws JpegProcessingException * @deprecated Not all files will be Jpegs! Use a constructor that provides * the exif segment in isolation. */ public ExifReader(File jpegFile) throws JpegProcessingException { // TODO consider removing this constructor and requiring callers to pass // a byte[] or other means to read the exif segment in isolation... not // all files will be Jpegs! this(new JpegSegmentReader(jpegFile) .readSegment(JpegSegmentReader.SEGMENT_APP1)); } /** * Creates an ExifReader for a Jpeg stream. * * @param jpegInputStream * JPEG stream. Stream will be closed. * @deprecated Not all files will be Jpegs! Use a constructor that provides * the exif segment in isolation. */ public ExifReader(InputStream jpegInputStream) throws JpegProcessingException { // TODO consider removing this constructor and requiring callers to pass // a byte[] or other means to read the exif segment in isolation... not // all files will be Jpegs! this(new JpegSegmentReader(jpegInputStream) .readSegment(JpegSegmentReader.SEGMENT_APP1)); } /** * Creates an ExifReader for the given Exif data segment. */ public ExifReader(byte[] data) { _data = data; } /** * Performs the Exif data extraction, returning a new instance of * <code>Metadata</code>. */ public Metadata extract() { return extract(new Metadata()); } /** * Performs the Exif data extraction, adding found values to the specified * instance of <code>Metadata</code>. */ public Metadata extract(Metadata metadata) { _metadata = metadata; if (_data == null) return _metadata; ExifDirectory directory = getExifDirectory(); // check for the header length if (_data.length <= 14) { directory .addError("Exif data segment must contain at least 14 bytes"); return _metadata; } if (!isExifSegment(_data)) { // check for the header preamble directory.addError("Exif data segment doesn't begin with 'Exif'"); return _metadata; } return extractIFD(_metadata, TIFF_HEADER_START_OFFSET); } public static boolean isExifSegment(byte[] data) { if (data == null || data.length <= 14) { return false; } if (!"Exif\0\0".equals(new String(data, 0, 6))) { return false; } return true; } private ExifDirectory getExifDirectory() { if (_exifDirectory == null) { _exifDirectory = (ExifDirectory) _metadata .getDirectory(ExifDirectory.class); } return _exifDirectory; } /** * Performs the Exif data extraction on a Tiff/Raw, adding found values to * the specified instance of <code>Metadata</code>. */ public Metadata extractTiff(Metadata metadata) { return extractIFD(metadata, 0); } private Metadata extractIFD(Metadata metadata, int tiffHeaderOffset) { _metadata = metadata; if (_data == null) return _metadata; ExifDirectory directory = getExifDirectory(); // this should be either "MM" or "II" String byteOrderIdentifier = new String(_data, tiffHeaderOffset, 2); if (!setByteOrder(byteOrderIdentifier)) { directory .addError("Unclear distinction between Motorola/Intel byte ordering: " + byteOrderIdentifier); return _metadata; } // Check the next two values for correctness. if (get16Bits(2 + tiffHeaderOffset) != 0x2a) { directory .addError("Invalid Exif start - should have 0x2A at offset 8 in Exif header"); return _metadata; } int firstDirectoryOffset = get32Bits(4 + tiffHeaderOffset) + tiffHeaderOffset; // David Ekholm sent an digital camera image that has this problem if (firstDirectoryOffset >= _data.length - 1) { directory .addError("First exif directory offset is beyond end of Exif data segment"); // First directory normally starts 14 bytes in -- try it here and // catch another error in the worst case firstDirectoryOffset = 14; } HashMap processedDirectoryOffsets = new HashMap(); // 0th IFD (we merge with Exif IFD) processDirectory(directory, processedDirectoryOffsets, firstDirectoryOffset, tiffHeaderOffset,0); // after the extraction process, if we have the correct tags, we may be // able to store thumbnail information storeThumbnailBytes(directory, tiffHeaderOffset); return _metadata; } private void storeThumbnailBytes(ExifDirectory exifDirectory, int tiffHeaderOffset) { if (!exifDirectory.containsTag(ExifDirectory.TAG_COMPRESSION)) return; if (!exifDirectory.containsTag(ExifDirectory.TAG_THUMBNAIL_LENGTH) || !exifDirectory .containsTag(ExifDirectory.TAG_THUMBNAIL_OFFSET)) return; try { int offset = exifDirectory .getInt(ExifDirectory.TAG_THUMBNAIL_OFFSET); int length = exifDirectory .getInt(ExifDirectory.TAG_THUMBNAIL_LENGTH); byte[] result = new byte[length]; for (int i = 0; i < result.length; i++) { result[i] = _data[tiffHeaderOffset + offset + i]; } exifDirectory .setByteArray(ExifDirectory.TAG_THUMBNAIL_DATA, result); } catch (Throwable e) { exifDirectory.addError("Unable to extract thumbnail: " + e.getMessage()); } } /** * Sets the _isMotorollaByteOrder flag to true or false, depending upon the * file's byte order string. If the string cannot be interpreted, false is * returned. * * @param byteOrderIdentifier * a two-character string; either "MM" for Motorolla or "II" for * Intel. * @return true if successful, otherwise false. */ private boolean setByteOrder(String byteOrderIdentifier) { if ("MM".equals(byteOrderIdentifier)) { _isMotorollaByteOrder = true; } else if ("II".equals(byteOrderIdentifier)) { _isMotorollaByteOrder = false; } else { return false; } return true; } /** * Process one of the nested Tiff IFD directories. 2 bytes: number of tags * for each tag 2 bytes: tag type 2 bytes: format code 4 bytes: component * count */ private void processDirectory(Directory directory, HashMap processedDirectoryOffsets, int dirStartOffset, int tiffHeaderOffset, int offsetSchema) { List makerNoteOffsets=new LinkedList(); boolean switchedByteOrder=false; do { // check for directories we've already visited to avoid stack overflows // when recursive/cyclic directory structures exist if (processedDirectoryOffsets.containsKey(new Integer(dirStartOffset))) break; // remember that we've visited this directory so that we don't visit it // again later processedDirectoryOffsets.put(new Integer(dirStartOffset), "processed"); if (dirStartOffset >= _data.length || dirStartOffset < 0) { directory .addError("Ignored directory marked to start outside data segement"); break; } if (! isDirectoryLengthValid(dirStartOffset, tiffHeaderOffset)) { /** * some tools (windows vista) modify the byte order for the EXIF data, * but copy the MakerNote bytes without switching byte order. * This flag temporarily switches byte order while processing a makernote dir */ _isMotorollaByteOrder=!_isMotorollaByteOrder; switchedByteOrder=true; if (! isDirectoryLengthValid(dirStartOffset, tiffHeaderOffset)) { directory.addError("Illegally sized directory"); break; } } // First two bytes in the IFD are the number of tags in this directory int dirTagCount = get16Bits(dirStartOffset); // Handle each tag in this directory for (int tagNumber = 0; tagNumber < dirTagCount; tagNumber++) { final int tagOffset = calculateTagOffset(dirStartOffset, tagNumber); // 2 bytes for the tag type final int tagType = get16Bits(tagOffset); // 2 bytes for the format code final int formatCode = get16Bits(tagOffset + 2); if (formatCode < 1 || formatCode > MAX_FORMAT_CODE) { directory.addError("Invalid format code: " + formatCode); continue; } // 4 bytes dictate the number of components in this tag's data final int componentCount = get32Bits(tagOffset + 4); if (componentCount < 0) { directory.addError("Negative component count in EXIF"); continue; } // each component may have more than one byte... calculate the total // number of bytes final int byteCount = componentCount * BYTES_PER_FORMAT[formatCode]; final int tagValueOffset = calculateTagValueOffset(byteCount, tagOffset, tiffHeaderOffset,offsetSchema); if (tagValueOffset < 0 || tagValueOffset > _data.length) { directory.addError("Illegal pointer offset value in EXIF"); continue; } // Check that this tag isn't going to allocate outside the bounds of // the data array. // This addresses an uncommon OutOfMemoryError. if (byteCount < 0 || tagValueOffset + byteCount > _data.length) { directory.addError("Illegal number of bytes: " + byteCount); continue; } // Calculate the value as an offset for cases where the tag // represents directory final int subdirOffset = tiffHeaderOffset + get32Bits(tagValueOffset); switch (tagType) { case TAG_EXIF_OFFSET: processDirectory(_metadata.getDirectory(ExifDirectory.class), processedDirectoryOffsets, subdirOffset, tiffHeaderOffset,offsetSchema); continue; case TAG_INTEROP_OFFSET: processDirectory(_metadata .getDirectory(ExifInteropDirectory.class), processedDirectoryOffsets, subdirOffset, tiffHeaderOffset,offsetSchema); continue; case TAG_GPS_INFO_OFFSET: processDirectory(_metadata.getDirectory(GpsDirectory.class), processedDirectoryOffsets, subdirOffset, tiffHeaderOffset,offsetSchema); continue; case TAG_MAKER_NOTE: makerNoteOffsets.add(new Integer(tagValueOffset)); continue; default: processTag(directory, tagType, tagValueOffset, componentCount, formatCode); break; } } // at the end of each IFD is an optional link to the next IFD final int finalTagOffset = calculateTagOffset(dirStartOffset, dirTagCount); int nextDirectoryOffset = get32Bits(finalTagOffset); if (nextDirectoryOffset != 0) { nextDirectoryOffset += tiffHeaderOffset; if (nextDirectoryOffset >= _data.length) { // Last 4 bytes of IFD reference another IFD with an address // that is out of bounds // Note this could have been caused by jhead 1.3 cropping too // much break; } else if (nextDirectoryOffset < dirStartOffset) { // Last 4 bytes of IFD reference another IFD with an address // that is before the start of this directory break; } // the next directory is of same type as this one } dirStartOffset=nextDirectoryOffset; } while ( dirStartOffset!=0 ); // process makerNotes if ( offsetSchema==0){ try { offsetSchema=directory.getInt(ExifDirectory.TAG_OFFSET_SCHEMA); } catch (MetadataException e){ offsetSchema=0; } } for (Iterator it = makerNoteOffsets.iterator(); it .hasNext();) { Integer offset = (Integer) it.next(); processMakerNote(offset.intValue(), processedDirectoryOffsets, tiffHeaderOffset,offsetSchema); } if ( switchedByteOrder) _isMotorollaByteOrder=!_isMotorollaByteOrder; } private void processMakerNote(int subdirOffset, HashMap processedDirectoryOffsets, int tiffHeaderOffset, int offsetSchema) { // Determine the camera model and makernote format Directory exifDirectory = _metadata.getDirectory(ExifDirectory.class); if (exifDirectory == null) return; String cameraModel = exifDirectory.getString(ExifDirectory.TAG_MAKE); final String firstTwoChars = new String(_data, subdirOffset, 2); final String firstThreeChars = new String(_data, subdirOffset, 3); final String firstFourChars = new String(_data, subdirOffset, 4); final String firstFiveChars = new String(_data, subdirOffset, 5); final String firstSixChars = new String(_data, subdirOffset, 6); final String firstSevenChars = new String(_data, subdirOffset, 7); final String firstEightChars = new String(_data, subdirOffset, 8); if ("OLYMP".equals(firstFiveChars) || "EPSON".equals(firstFiveChars) || "AGFA".equals(firstFourChars)) { // Olympus Makernote // Epson and Agfa use Olypus maker note standard, see: // http://www.ozhiker.com/electronics/pjmt/jpeg_info/ processDirectory(_metadata .getDirectory(OlympusMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 8, tiffHeaderOffset,offsetSchema); } else if (cameraModel != null && cameraModel.trim().toUpperCase().startsWith("NIKON")) { if ("Nikon".equals(firstFiveChars)) { /* * There are two scenarios here: * * Type 1: ** * * :0000: 4E 69 6B 6F 6E 00 01 00-05 00 02 00 02 00 06 00 Nikon........... * :0010: 00 00 EC 02 00 00 03 00-03 00 01 00 00 00 06 00 ................ * * Type 3: ** * * :0000: 4E 69 6B 6F 6E 00 02 00-00 00 4D 4D 00 2A 00 00 Nikon....MM.*... * :0010: 00 08 00 1E 00 01 00 07-00 00 00 04 30 32 30 30 ............0200 */ if (_data[subdirOffset + 6] == 1) processDirectory(_metadata .getDirectory(NikonType1MakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 8, tiffHeaderOffset,offsetSchema); else if (_data[subdirOffset + 6] == 2) processDirectory(_metadata .getDirectory(NikonType2MakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 18, subdirOffset + 10,offsetSchema); else exifDirectory .addError("Unsupported makernote data ignored."); } else { // The IFD begins with the first MakerNote byte (no ASCII name). // This occurs with CoolPix 775, E990 and D1 models. processDirectory(_metadata .getDirectory(NikonType2MakernoteDirectory.class), processedDirectoryOffsets, subdirOffset, tiffHeaderOffset,offsetSchema); } } else if ("SONY CAM".equals(firstEightChars) || "SONY DSC".equals(firstEightChars)) { processDirectory(_metadata .getDirectory(SonyMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 12, tiffHeaderOffset,offsetSchema); } else if ("KDK".equals(firstThreeChars)) { processDirectory(_metadata .getDirectory(KodakMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 20, tiffHeaderOffset,offsetSchema); } else if ("Canon".equalsIgnoreCase(cameraModel)) { processDirectory(_metadata .getDirectory(CanonMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset, tiffHeaderOffset,offsetSchema); } else if (cameraModel != null && cameraModel.toUpperCase().startsWith("CASIO")) { if ("QVC\u0000\u0000\u0000".equals(firstSixChars)) processDirectory(_metadata .getDirectory(CasioType2MakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 6, tiffHeaderOffset,offsetSchema); else processDirectory(_metadata .getDirectory(CasioType1MakernoteDirectory.class), processedDirectoryOffsets, subdirOffset, tiffHeaderOffset,offsetSchema); } else if ("FUJIFILM".equals(firstEightChars) || "Fujifilm".equalsIgnoreCase(cameraModel)) { // TODO make this field a passed parameter, to avoid threading // issues boolean byteOrderBefore = _isMotorollaByteOrder; // bug in fujifilm makernote ifd means we temporarily use Intel byte // ordering _isMotorollaByteOrder = false; // the 4 bytes after "FUJIFILM" in the makernote point to the start // of the makernote // IFD, though the offset is relative to the start of the makernote, // not the TIFF // header (like everywhere else) int ifdStart = subdirOffset + get32Bits(subdirOffset + 8); processDirectory(_metadata .getDirectory(FujifilmMakernoteDirectory.class), processedDirectoryOffsets, ifdStart, tiffHeaderOffset,offsetSchema); _isMotorollaByteOrder = byteOrderBefore; } else if (cameraModel != null && cameraModel.toUpperCase().startsWith("MINOLTA")) { // Cases seen with the model starting with MINOLTA in capitals seem // to have a valid Olympus makernote // area that commences immediately. processDirectory(_metadata .getDirectory(OlympusMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset, tiffHeaderOffset,offsetSchema); } else if ("KC".equals(firstTwoChars) || "MINOL".equals(firstFiveChars) || "MLY".equals(firstThreeChars) || "+M+M+M+M".equals(firstEightChars)) { // This Konica data is not understood. Header identified in // accordance with information at this site: // http://www.ozhiker.com/electronics/pjmt/jpeg_info/minolta_mn.html // TODO determine how to process the information described at the // above website exifDirectory.addError("Unsupported Konica/Minolta data ignored."); } else if ("KYOCERA".equals(firstSevenChars)) { // http://www.ozhiker.com/electronics/pjmt/jpeg_info/kyocera_mn.html processDirectory(_metadata .getDirectory(KyoceraMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 22, tiffHeaderOffset,offsetSchema); } else if ("Panasonic\u0000\u0000\u0000".equals(new String(_data, subdirOffset, 12))) { // NON-Standard TIFF IFD Data using Panasonic Tags. There is no // Next-IFD pointer after the IFD // Offsets are relative to the start of the TIFF header at the // beginning of the EXIF segment // more information here: // http://www.ozhiker.com/electronics/pjmt/jpeg_info/panasonic_mn.html processDirectory(_metadata .getDirectory(PanasonicMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 12, tiffHeaderOffset,offsetSchema); } else if ("AOC\u0000".equals(firstFourChars)) { // NON-Standard TIFF IFD Data using Casio Type 2 Tags // IFD has no Next-IFD pointer at end of IFD, and // Offsets are relative to the start of the current IFD tag, not the // TIFF header // Observed for: // - Pentax ist D processDirectory(_metadata .getDirectory(CasioType2MakernoteDirectory.class), processedDirectoryOffsets, subdirOffset + 6, subdirOffset,offsetSchema); } else if (cameraModel != null && (cameraModel.toUpperCase().startsWith("PENTAX") || cameraModel .toUpperCase().startsWith("ASAHI"))) { // NON-Standard TIFF IFD Data using Pentax Tags // IFD has no Next-IFD pointer at end of IFD, and // Offsets are relative to the start of the current IFD tag, not the // TIFF header // Observed for: // - PENTAX Optio 330 // - PENTAX Optio 430 processDirectory(_metadata .getDirectory(PentaxMakernoteDirectory.class), processedDirectoryOffsets, subdirOffset, subdirOffset,offsetSchema); } else { // TODO how to store makernote data when it's not from a supported // camera model? // this is difficult as the starting offset is not known. we could // look for it... exifDirectory.addError("Unsupported makernote data ignored."); } } private boolean isDirectoryLengthValid(int dirStartOffset, int tiffHeaderOffset) { int dirTagCount = get16Bits(dirStartOffset); int dirLength = (2 + (12 * dirTagCount) + 4); if (dirLength + dirStartOffset + tiffHeaderOffset >= _data.length) { // Note: Files that had thumbnails trimmed with jhead 1.3 or earlier // might trigger this return false; } return true; } private void processTag(Directory directory, int tagType, int tagValueOffset, int componentCount, int formatCode) { // Directory simply stores raw values // The display side uses a Descriptor class per directory to turn the // raw values into 'pretty' descriptions switch (formatCode) { case FMT_UNDEFINED: // this includes exif user comments final byte[] tagBytes = new byte[componentCount]; final int byteCount = componentCount * BYTES_PER_FORMAT[formatCode]; for (int i = 0; i < byteCount; i++) tagBytes[i] = _data[tagValueOffset + i]; directory.setByteArray(tagType, tagBytes); break; case FMT_STRING: directory.setString(tagType, readString(tagValueOffset, componentCount)); break; case FMT_SRATIONAL: case FMT_URATIONAL: if (componentCount == 1) { Rational rational = new Rational(get32Bits(tagValueOffset), get32Bits(tagValueOffset + 4)); directory.setRational(tagType, rational); } else { Rational[] rationals = new Rational[componentCount]; for (int i = 0; i < componentCount; i++) rationals[i] = new Rational(get32Bits(tagValueOffset + (8 * i)), get32Bits(tagValueOffset + 4 + (8 * i))); directory.setRationalArray(tagType, rationals); } break; case FMT_SBYTE: case FMT_BYTE: if (componentCount == 1) { // this may need to be a byte, but I think casting to int is // fine int b = _data[tagValueOffset]; directory.setInt(tagType, b); } else { int[] bytes = new int[componentCount]; for (int i = 0; i < componentCount; i++) bytes[i] = _data[tagValueOffset + i]; directory.setIntArray(tagType, bytes); } break; case FMT_SINGLE: case FMT_DOUBLE: if (componentCount == 1) { int i = _data[tagValueOffset]; directory.setInt(tagType, i); } else { int[] ints = new int[componentCount]; for (int i = 0; i < componentCount; i++) ints[i] = _data[tagValueOffset + i]; directory.setIntArray(tagType, ints); } break; case FMT_USHORT: case FMT_SSHORT: if (componentCount == 1) { int i = get16Bits(tagValueOffset); directory.setInt(tagType, i); } else { int[] ints = new int[componentCount]; for (int i = 0; i < componentCount; i++) ints[i] = get16Bits(tagValueOffset + (i * 2)); directory.setIntArray(tagType, ints); } break; case FMT_SLONG: case FMT_ULONG: if (componentCount == 1) { int i = get32Bits(tagValueOffset); directory.setInt(tagType, i); } else { int[] ints = new int[componentCount]; for (int i = 0; i < componentCount; i++) ints[i] = get32Bits(tagValueOffset + (i * 4)); directory.setIntArray(tagType, ints); } break; default: directory.addError("Unknown format code " + formatCode + " for tag " + tagType); } } private int calculateTagValueOffset(int byteCount, int dirEntryOffset, int tiffHeaderOffset, int offsetSchema) { if (byteCount > 4) { // If its bigger than 4 bytes, the dir entry contains an offset. // dirEntryOffset must be passed, as some makernote implementations // (e.g. FujiFilm) incorrectly use an // offset relative to the start of the makernote itself, not the // TIFF segment. final int offsetVal = get32Bits(dirEntryOffset + 8)+offsetSchema; if (offsetVal + byteCount > _data.length) { // Bogus pointer offset and / or bytecount value return -1; // signal error } return tiffHeaderOffset + offsetVal; } else { // 4 bytes or less and value is in the dir entry itself return dirEntryOffset + 8; } } /** * Creates a String from the _data buffer starting at the specified offset, * and ending where byte=='\0' or where length==maxLength. */ private String readString(int offset, int maxLength) { int length = 0; while ((offset + length) < _data.length && _data[offset + length] != '\0' && length < maxLength) length++; return new String(_data, offset, length); } /** * Determine the offset at which a given InteropArray entry begins within * the specified IFD. * * @param dirStartOffset * the offset at which the IFD starts * @param entryNumber * the zero-based entry number */ private int calculateTagOffset(int dirStartOffset, int entryNumber) { // add 2 bytes for the tag count // each entry is 12 bytes, so we skip 12 * the number seen so far return dirStartOffset + 2 + (12 * entryNumber); } /** * Get a 16 bit value from file's native byte order. Between 0x0000 and * 0xFFFF. */ private int get16Bits(int offset) { if (offset < 0 || offset + 2 > _data.length) throw new ArrayIndexOutOfBoundsException( "attempt to read data outside of exif segment (index " + offset + " where max index is " + (_data.length - 1) + ")"); if (_isMotorollaByteOrder) { // Motorola - MSB first return (_data[offset] << 8 & 0xFF00) | (_data[offset + 1] & 0xFF); } else { // Intel ordering - LSB first return (_data[offset + 1] << 8 & 0xFF00) | (_data[offset] & 0xFF); } } /** * Get a 32 bit value from file's native byte order. */ private int get32Bits(int offset) { if (offset < 0 || offset + 4 > _data.length) throw new ArrayIndexOutOfBoundsException( "attempt to read data outside of exif segment (index " + offset + " where max index is " + (_data.length - 1) + ")"); if (_isMotorollaByteOrder) { // Motorola - MSB first return (_data[offset] << 24 & 0xFF000000) | (_data[offset + 1] << 16 & 0xFF0000) | (_data[offset + 2] << 8 & 0xFF00) | (_data[offset + 3] & 0xFF); } else { // Intel ordering - LSB first return (_data[offset + 3] << 24 & 0xFF000000) | (_data[offset + 2] << 16 & 0xFF0000) | (_data[offset + 1] << 8 & 0xFF00) | (_data[offset] & 0xFF); } } }
googleapis/google-cloud-java
36,332
java-chat/proto-google-cloud-chat-v1/src/main/java/com/google/chat/v1/ListSpacesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/chat/v1/space.proto // Protobuf Java Version: 3.25.8 package com.google.chat.v1; /** * * * <pre> * The response for a list spaces request. * </pre> * * Protobuf type {@code google.chat.v1.ListSpacesResponse} */ public final class ListSpacesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.chat.v1.ListSpacesResponse) ListSpacesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListSpacesResponse.newBuilder() to construct. private ListSpacesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListSpacesResponse() { spaces_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListSpacesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chat.v1.SpaceProto .internal_static_google_chat_v1_ListSpacesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chat.v1.SpaceProto .internal_static_google_chat_v1_ListSpacesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chat.v1.ListSpacesResponse.class, com.google.chat.v1.ListSpacesResponse.Builder.class); } public static final int SPACES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.chat.v1.Space> spaces_; /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ @java.lang.Override public java.util.List<com.google.chat.v1.Space> getSpacesList() { return spaces_; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.chat.v1.SpaceOrBuilder> getSpacesOrBuilderList() { return spaces_; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ @java.lang.Override public int getSpacesCount() { return spaces_.size(); } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ @java.lang.Override public com.google.chat.v1.Space getSpaces(int index) { return spaces_.get(index); } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ @java.lang.Override public com.google.chat.v1.SpaceOrBuilder getSpacesOrBuilder(int index) { return spaces_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * You can send a token as `pageToken` to retrieve the next page of * results. If empty, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * You can send a token as `pageToken` to retrieve the next page of * results. If empty, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < spaces_.size(); i++) { output.writeMessage(1, spaces_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < spaces_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, spaces_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.chat.v1.ListSpacesResponse)) { return super.equals(obj); } com.google.chat.v1.ListSpacesResponse other = (com.google.chat.v1.ListSpacesResponse) obj; if (!getSpacesList().equals(other.getSpacesList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getSpacesCount() > 0) { hash = (37 * hash) + SPACES_FIELD_NUMBER; hash = (53 * hash) + getSpacesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.chat.v1.ListSpacesResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.ListSpacesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chat.v1.ListSpacesResponse parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.ListSpacesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chat.v1.ListSpacesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.ListSpacesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chat.v1.ListSpacesResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.chat.v1.ListSpacesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.chat.v1.ListSpacesResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.chat.v1.ListSpacesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.chat.v1.ListSpacesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.chat.v1.ListSpacesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.chat.v1.ListSpacesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response for a list spaces request. * </pre> * * Protobuf type {@code google.chat.v1.ListSpacesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.chat.v1.ListSpacesResponse) com.google.chat.v1.ListSpacesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chat.v1.SpaceProto .internal_static_google_chat_v1_ListSpacesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chat.v1.SpaceProto .internal_static_google_chat_v1_ListSpacesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chat.v1.ListSpacesResponse.class, com.google.chat.v1.ListSpacesResponse.Builder.class); } // Construct using com.google.chat.v1.ListSpacesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (spacesBuilder_ == null) { spaces_ = java.util.Collections.emptyList(); } else { spaces_ = null; spacesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.chat.v1.SpaceProto .internal_static_google_chat_v1_ListSpacesResponse_descriptor; } @java.lang.Override public com.google.chat.v1.ListSpacesResponse getDefaultInstanceForType() { return com.google.chat.v1.ListSpacesResponse.getDefaultInstance(); } @java.lang.Override public com.google.chat.v1.ListSpacesResponse build() { com.google.chat.v1.ListSpacesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.chat.v1.ListSpacesResponse buildPartial() { com.google.chat.v1.ListSpacesResponse result = new com.google.chat.v1.ListSpacesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.chat.v1.ListSpacesResponse result) { if (spacesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { spaces_ = java.util.Collections.unmodifiableList(spaces_); bitField0_ = (bitField0_ & ~0x00000001); } result.spaces_ = spaces_; } else { result.spaces_ = spacesBuilder_.build(); } } private void buildPartial0(com.google.chat.v1.ListSpacesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.chat.v1.ListSpacesResponse) { return mergeFrom((com.google.chat.v1.ListSpacesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.chat.v1.ListSpacesResponse other) { if (other == com.google.chat.v1.ListSpacesResponse.getDefaultInstance()) return this; if (spacesBuilder_ == null) { if (!other.spaces_.isEmpty()) { if (spaces_.isEmpty()) { spaces_ = other.spaces_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSpacesIsMutable(); spaces_.addAll(other.spaces_); } onChanged(); } } else { if (!other.spaces_.isEmpty()) { if (spacesBuilder_.isEmpty()) { spacesBuilder_.dispose(); spacesBuilder_ = null; spaces_ = other.spaces_; bitField0_ = (bitField0_ & ~0x00000001); spacesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSpacesFieldBuilder() : null; } else { spacesBuilder_.addAllMessages(other.spaces_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.chat.v1.Space m = input.readMessage(com.google.chat.v1.Space.parser(), extensionRegistry); if (spacesBuilder_ == null) { ensureSpacesIsMutable(); spaces_.add(m); } else { spacesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.chat.v1.Space> spaces_ = java.util.Collections.emptyList(); private void ensureSpacesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { spaces_ = new java.util.ArrayList<com.google.chat.v1.Space>(spaces_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.chat.v1.Space, com.google.chat.v1.Space.Builder, com.google.chat.v1.SpaceOrBuilder> spacesBuilder_; /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public java.util.List<com.google.chat.v1.Space> getSpacesList() { if (spacesBuilder_ == null) { return java.util.Collections.unmodifiableList(spaces_); } else { return spacesBuilder_.getMessageList(); } } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public int getSpacesCount() { if (spacesBuilder_ == null) { return spaces_.size(); } else { return spacesBuilder_.getCount(); } } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public com.google.chat.v1.Space getSpaces(int index) { if (spacesBuilder_ == null) { return spaces_.get(index); } else { return spacesBuilder_.getMessage(index); } } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder setSpaces(int index, com.google.chat.v1.Space value) { if (spacesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSpacesIsMutable(); spaces_.set(index, value); onChanged(); } else { spacesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder setSpaces(int index, com.google.chat.v1.Space.Builder builderForValue) { if (spacesBuilder_ == null) { ensureSpacesIsMutable(); spaces_.set(index, builderForValue.build()); onChanged(); } else { spacesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder addSpaces(com.google.chat.v1.Space value) { if (spacesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSpacesIsMutable(); spaces_.add(value); onChanged(); } else { spacesBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder addSpaces(int index, com.google.chat.v1.Space value) { if (spacesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSpacesIsMutable(); spaces_.add(index, value); onChanged(); } else { spacesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder addSpaces(com.google.chat.v1.Space.Builder builderForValue) { if (spacesBuilder_ == null) { ensureSpacesIsMutable(); spaces_.add(builderForValue.build()); onChanged(); } else { spacesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder addSpaces(int index, com.google.chat.v1.Space.Builder builderForValue) { if (spacesBuilder_ == null) { ensureSpacesIsMutable(); spaces_.add(index, builderForValue.build()); onChanged(); } else { spacesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder addAllSpaces(java.lang.Iterable<? extends com.google.chat.v1.Space> values) { if (spacesBuilder_ == null) { ensureSpacesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, spaces_); onChanged(); } else { spacesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder clearSpaces() { if (spacesBuilder_ == null) { spaces_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { spacesBuilder_.clear(); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public Builder removeSpaces(int index) { if (spacesBuilder_ == null) { ensureSpacesIsMutable(); spaces_.remove(index); onChanged(); } else { spacesBuilder_.remove(index); } return this; } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public com.google.chat.v1.Space.Builder getSpacesBuilder(int index) { return getSpacesFieldBuilder().getBuilder(index); } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public com.google.chat.v1.SpaceOrBuilder getSpacesOrBuilder(int index) { if (spacesBuilder_ == null) { return spaces_.get(index); } else { return spacesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public java.util.List<? extends com.google.chat.v1.SpaceOrBuilder> getSpacesOrBuilderList() { if (spacesBuilder_ != null) { return spacesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(spaces_); } } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public com.google.chat.v1.Space.Builder addSpacesBuilder() { return getSpacesFieldBuilder().addBuilder(com.google.chat.v1.Space.getDefaultInstance()); } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public com.google.chat.v1.Space.Builder addSpacesBuilder(int index) { return getSpacesFieldBuilder() .addBuilder(index, com.google.chat.v1.Space.getDefaultInstance()); } /** * * * <pre> * List of spaces in the requested (or first) page. * Note: The `permissionSettings` field is not returned in the Space * object for list requests. * </pre> * * <code>repeated .google.chat.v1.Space spaces = 1;</code> */ public java.util.List<com.google.chat.v1.Space.Builder> getSpacesBuilderList() { return getSpacesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.chat.v1.Space, com.google.chat.v1.Space.Builder, com.google.chat.v1.SpaceOrBuilder> getSpacesFieldBuilder() { if (spacesBuilder_ == null) { spacesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.chat.v1.Space, com.google.chat.v1.Space.Builder, com.google.chat.v1.SpaceOrBuilder>( spaces_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); spaces_ = null; } return spacesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * You can send a token as `pageToken` to retrieve the next page of * results. If empty, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * You can send a token as `pageToken` to retrieve the next page of * results. If empty, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * You can send a token as `pageToken` to retrieve the next page of * results. If empty, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * You can send a token as `pageToken` to retrieve the next page of * results. If empty, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * You can send a token as `pageToken` to retrieve the next page of * results. If empty, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.chat.v1.ListSpacesResponse) } // @@protoc_insertion_point(class_scope:google.chat.v1.ListSpacesResponse) private static final com.google.chat.v1.ListSpacesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.chat.v1.ListSpacesResponse(); } public static com.google.chat.v1.ListSpacesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListSpacesResponse> PARSER = new com.google.protobuf.AbstractParser<ListSpacesResponse>() { @java.lang.Override public ListSpacesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListSpacesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListSpacesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.chat.v1.ListSpacesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/dubbo
36,416
dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfoV2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.metadata; /** * <pre> * Metadata information message. * </pre> * * Protobuf type {@code org.apache.dubbo.metadata.MetadataInfoV2} */ public final class MetadataInfoV2 extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.MetadataInfoV2) MetadataInfoV2OrBuilder { private static final long serialVersionUID = 0L; // Use MetadataInfoV2.newBuilder() to construct. private MetadataInfoV2(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MetadataInfoV2() { app_ = ""; version_ = ""; } @Override @SuppressWarnings({"unused"}) protected Object newInstance(UnusedPrivateParameter unused) { return new MetadataInfoV2(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor; } @SuppressWarnings({"rawtypes"}) @Override protected com.google.protobuf.MapField internalGetMapField(int number) { switch (number) { case 3: return internalGetServices(); default: throw new RuntimeException("Invalid map field number: " + number); } } @Override protected FieldAccessorTable internalGetFieldAccessorTable() { return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_fieldAccessorTable .ensureFieldAccessorsInitialized(MetadataInfoV2.class, Builder.class); } public static final int APP_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile Object app_ = ""; /** * <pre> * The application name. * </pre> * * <code>string app = 1;</code> * @return The app. */ @Override public String getApp() { Object ref = app_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); app_ = s; return s; } } /** * <pre> * The application name. * </pre> * * <code>string app = 1;</code> * @return The bytes for app. */ @Override public com.google.protobuf.ByteString getAppBytes() { Object ref = app_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); app_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VERSION_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile Object version_ = ""; /** * <pre> * The application version. * </pre> * * <code>string version = 2;</code> * @return The version. */ @Override public String getVersion() { Object ref = version_; if (ref instanceof String) { return (String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); version_ = s; return s; } } /** * <pre> * The application version. * </pre> * * <code>string version = 2;</code> * @return The bytes for version. */ @Override public com.google.protobuf.ByteString getVersionBytes() { Object ref = version_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); version_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICES_FIELD_NUMBER = 3; private static final class ServicesDefaultEntryHolder { static final com.google.protobuf.MapEntry<String, ServiceInfoV2> defaultEntry = com.google.protobuf.MapEntry.<String, ServiceInfoV2>newDefaultInstance( MetadataServiceV2OuterClass .internal_static_org_apache_dubbo_metadata_MetadataInfoV2_ServicesEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.MESSAGE, ServiceInfoV2.getDefaultInstance()); } @SuppressWarnings("serial") private com.google.protobuf.MapField<String, ServiceInfoV2> services_; private com.google.protobuf.MapField<String, ServiceInfoV2> internalGetServices() { if (services_ == null) { return com.google.protobuf.MapField.emptyMapField(ServicesDefaultEntryHolder.defaultEntry); } return services_; } public int getServicesCount() { return internalGetServices().getMap().size(); } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public boolean containsServices(String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetServices().getMap().containsKey(key); } /** * Use {@link #getServicesMap()} instead. */ @Override @Deprecated public java.util.Map<String, ServiceInfoV2> getServices() { return getServicesMap(); } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public java.util.Map<String, ServiceInfoV2> getServicesMap() { return internalGetServices().getMap(); } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public /* nullable */ ServiceInfoV2 getServicesOrDefault( String key, /* nullable */ ServiceInfoV2 defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public ServiceInfoV2 getServicesOrThrow(String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap(); if (!map.containsKey(key)) { throw new IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) { return true; } if (isInitialized == 0) { return false; } memoizedIsInitialized = 1; return true; } @Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(app_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, app_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, version_); } com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetServices(), ServicesDefaultEntryHolder.defaultEntry, 3); getUnknownFields().writeTo(output); } @Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) { return size; } size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(app_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, app_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, version_); } for (java.util.Map.Entry<String, ServiceInfoV2> entry : internalGetServices().getMap().entrySet()) { com.google.protobuf.MapEntry<String, ServiceInfoV2> services__ = ServicesDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, services__); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof MetadataInfoV2)) { return super.equals(obj); } MetadataInfoV2 other = (MetadataInfoV2) obj; if (!getApp().equals(other.getApp())) { return false; } if (!getVersion().equals(other.getVersion())) { return false; } if (!internalGetServices().equals(other.internalGetServices())) { return false; } if (!getUnknownFields().equals(other.getUnknownFields())) { return false; } return true; } @Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + APP_FIELD_NUMBER; hash = (53 * hash) + getApp().hashCode(); hash = (37 * hash) + VERSION_FIELD_NUMBER; hash = (53 * hash) + getVersion().hashCode(); if (!internalGetServices().getMap().isEmpty()) { hash = (37 * hash) + SERVICES_FIELD_NUMBER; hash = (53 * hash) + internalGetServices().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static MetadataInfoV2 parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static MetadataInfoV2 parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static MetadataInfoV2 parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static MetadataInfoV2 parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static MetadataInfoV2 parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static MetadataInfoV2 parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static MetadataInfoV2 parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static MetadataInfoV2 parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); } public static MetadataInfoV2 parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static MetadataInfoV2 parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static MetadataInfoV2 parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static MetadataInfoV2 parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); } @Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(MetadataInfoV2 prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @Override protected Builder newBuilderForType(BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Metadata information message. * </pre> * * Protobuf type {@code org.apache.dubbo.metadata.MetadataInfoV2} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.MetadataInfoV2) MetadataInfoV2OrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField(int number) { switch (number) { case 3: return internalGetServices(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMutableMapField(int number) { switch (number) { case 3: return internalGetMutableServices(); default: throw new RuntimeException("Invalid map field number: " + number); } } @Override protected FieldAccessorTable internalGetFieldAccessorTable() { return MetadataServiceV2OuterClass .internal_static_org_apache_dubbo_metadata_MetadataInfoV2_fieldAccessorTable .ensureFieldAccessorsInitialized(MetadataInfoV2.class, Builder.class); } // Construct using org.apache.dubbo.metadata.MetadataInfoV2.newBuilder() private Builder() {} private Builder(BuilderParent parent) { super(parent); } @Override public Builder clear() { super.clear(); bitField0_ = 0; app_ = ""; version_ = ""; internalGetMutableServices().clear(); return this; } @Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor; } @Override public MetadataInfoV2 getDefaultInstanceForType() { return MetadataInfoV2.getDefaultInstance(); } @Override public MetadataInfoV2 build() { MetadataInfoV2 result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @Override public MetadataInfoV2 buildPartial() { MetadataInfoV2 result = new MetadataInfoV2(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(MetadataInfoV2 result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.app_ = app_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.version_ = version_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.services_ = internalGetServices(); result.services_.makeImmutable(); } } @Override public Builder clone() { return super.clone(); } @Override public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return super.setField(field, value); } @Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return super.setRepeatedField(field, index, value); } @Override public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return super.addRepeatedField(field, value); } @Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof MetadataInfoV2) { return mergeFrom((MetadataInfoV2) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(MetadataInfoV2 other) { if (other == MetadataInfoV2.getDefaultInstance()) { return this; } if (!other.getApp().isEmpty()) { app_ = other.app_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getVersion().isEmpty()) { version_ = other.version_; bitField0_ |= 0x00000002; onChanged(); } internalGetMutableServices().mergeFrom(other.internalGetServices()); bitField0_ |= 0x00000004; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @Override public final boolean isInitialized() { return true; } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { app_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { version_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { com.google.protobuf.MapEntry<String, ServiceInfoV2> services__ = input.readMessage( ServicesDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableServices() .getMutableMap() .put(services__.getKey(), services__.getValue()); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private Object app_ = ""; /** * <pre> * The application name. * </pre> * * <code>string app = 1;</code> * @return The app. */ public String getApp() { Object ref = app_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); app_ = s; return s; } else { return (String) ref; } } /** * <pre> * The application name. * </pre> * * <code>string app = 1;</code> * @return The bytes for app. */ public com.google.protobuf.ByteString getAppBytes() { Object ref = app_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); app_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The application name. * </pre> * * <code>string app = 1;</code> * @param value The app to set. * @return This builder for chaining. */ public Builder setApp(String value) { if (value == null) { throw new NullPointerException(); } app_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * The application name. * </pre> * * <code>string app = 1;</code> * @return This builder for chaining. */ public Builder clearApp() { app_ = getDefaultInstance().getApp(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * The application name. * </pre> * * <code>string app = 1;</code> * @param value The bytes for app to set. * @return This builder for chaining. */ public Builder setAppBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); app_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private Object version_ = ""; /** * <pre> * The application version. * </pre> * * <code>string version = 2;</code> * @return The version. */ public String getVersion() { Object ref = version_; if (!(ref instanceof String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; String s = bs.toStringUtf8(); version_ = s; return s; } else { return (String) ref; } } /** * <pre> * The application version. * </pre> * * <code>string version = 2;</code> * @return The bytes for version. */ public com.google.protobuf.ByteString getVersionBytes() { Object ref = version_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); version_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The application version. * </pre> * * <code>string version = 2;</code> * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(String value) { if (value == null) { throw new NullPointerException(); } version_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * The application version. * </pre> * * <code>string version = 2;</code> * @return This builder for chaining. */ public Builder clearVersion() { version_ = getDefaultInstance().getVersion(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * The application version. * </pre> * * <code>string version = 2;</code> * @param value The bytes for version to set. * @return This builder for chaining. */ public Builder setVersionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); version_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.protobuf.MapField<String, ServiceInfoV2> services_; private com.google.protobuf.MapField<String, ServiceInfoV2> internalGetServices() { if (services_ == null) { return com.google.protobuf.MapField.emptyMapField(ServicesDefaultEntryHolder.defaultEntry); } return services_; } private com.google.protobuf.MapField<String, ServiceInfoV2> internalGetMutableServices() { if (services_ == null) { services_ = com.google.protobuf.MapField.newMapField(ServicesDefaultEntryHolder.defaultEntry); } if (!services_.isMutable()) { services_ = services_.copy(); } bitField0_ |= 0x00000004; onChanged(); return services_; } public int getServicesCount() { return internalGetServices().getMap().size(); } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public boolean containsServices(String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetServices().getMap().containsKey(key); } /** * Use {@link #getServicesMap()} instead. */ @Override @Deprecated public java.util.Map<String, ServiceInfoV2> getServices() { return getServicesMap(); } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public java.util.Map<String, ServiceInfoV2> getServicesMap() { return internalGetServices().getMap(); } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public /* nullable */ ServiceInfoV2 getServicesOrDefault( String key, /* nullable */ ServiceInfoV2 defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ @Override public ServiceInfoV2 getServicesOrThrow(String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap(); if (!map.containsKey(key)) { throw new IllegalArgumentException(); } return map.get(key); } public Builder clearServices() { bitField0_ = (bitField0_ & ~0x00000004); internalGetMutableServices().getMutableMap().clear(); return this; } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ public Builder removeServices(String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableServices().getMutableMap().remove(key); return this; } /** * Use alternate mutation accessors instead. */ @Deprecated public java.util.Map<String, ServiceInfoV2> getMutableServices() { bitField0_ |= 0x00000004; return internalGetMutableServices().getMutableMap(); } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ public Builder putServices(String key, ServiceInfoV2 value) { if (key == null) { throw new NullPointerException("map key"); } if (value == null) { throw new NullPointerException("map value"); } internalGetMutableServices().getMutableMap().put(key, value); bitField0_ |= 0x00000004; return this; } /** * <pre> * A map of service information. * </pre> * * <code>map&lt;string, .org.apache.dubbo.metadata.ServiceInfoV2&gt; services = 3;</code> */ public Builder putAllServices(java.util.Map<String, ServiceInfoV2> values) { internalGetMutableServices().getMutableMap().putAll(values); bitField0_ |= 0x00000004; return this; } @Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @Override public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.MetadataInfoV2) } // @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.MetadataInfoV2) private static final MetadataInfoV2 DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new MetadataInfoV2(); } public static MetadataInfoV2 getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MetadataInfoV2> PARSER = new com.google.protobuf.AbstractParser<MetadataInfoV2>() { @Override public MetadataInfoV2 parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<MetadataInfoV2> parser() { return PARSER; } @Override public com.google.protobuf.Parser<MetadataInfoV2> getParserForType() { return PARSER; } @Override public MetadataInfoV2 getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,378
java-dataflow/proto-google-cloud-dataflow-v1beta3/src/main/java/com/google/dataflow/v1beta3/Straggler.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/dataflow/v1beta3/metrics.proto // Protobuf Java Version: 3.25.8 package com.google.dataflow.v1beta3; /** * * * <pre> * Information for a straggler. * </pre> * * Protobuf type {@code google.dataflow.v1beta3.Straggler} */ public final class Straggler extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.dataflow.v1beta3.Straggler) StragglerOrBuilder { private static final long serialVersionUID = 0L; // Use Straggler.newBuilder() to construct. private Straggler(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Straggler() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Straggler(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.dataflow.v1beta3.MetricsProto .internal_static_google_dataflow_v1beta3_Straggler_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.dataflow.v1beta3.MetricsProto .internal_static_google_dataflow_v1beta3_Straggler_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.dataflow.v1beta3.Straggler.class, com.google.dataflow.v1beta3.Straggler.Builder.class); } private int stragglerInfoCase_ = 0; @SuppressWarnings("serial") private java.lang.Object stragglerInfo_; public enum StragglerInfoCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { BATCH_STRAGGLER(1), STREAMING_STRAGGLER(2), STRAGGLERINFO_NOT_SET(0); private final int value; private StragglerInfoCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static StragglerInfoCase valueOf(int value) { return forNumber(value); } public static StragglerInfoCase forNumber(int value) { switch (value) { case 1: return BATCH_STRAGGLER; case 2: return STREAMING_STRAGGLER; case 0: return STRAGGLERINFO_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public StragglerInfoCase getStragglerInfoCase() { return StragglerInfoCase.forNumber(stragglerInfoCase_); } public static final int BATCH_STRAGGLER_FIELD_NUMBER = 1; /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> * * @return Whether the batchStraggler field is set. */ @java.lang.Override public boolean hasBatchStraggler() { return stragglerInfoCase_ == 1; } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> * * @return The batchStraggler. */ @java.lang.Override public com.google.dataflow.v1beta3.StragglerInfo getBatchStraggler() { if (stragglerInfoCase_ == 1) { return (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StragglerInfo.getDefaultInstance(); } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ @java.lang.Override public com.google.dataflow.v1beta3.StragglerInfoOrBuilder getBatchStragglerOrBuilder() { if (stragglerInfoCase_ == 1) { return (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StragglerInfo.getDefaultInstance(); } public static final int STREAMING_STRAGGLER_FIELD_NUMBER = 2; /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> * * @return Whether the streamingStraggler field is set. */ @java.lang.Override public boolean hasStreamingStraggler() { return stragglerInfoCase_ == 2; } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> * * @return The streamingStraggler. */ @java.lang.Override public com.google.dataflow.v1beta3.StreamingStragglerInfo getStreamingStraggler() { if (stragglerInfoCase_ == 2) { return (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StreamingStragglerInfo.getDefaultInstance(); } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ @java.lang.Override public com.google.dataflow.v1beta3.StreamingStragglerInfoOrBuilder getStreamingStragglerOrBuilder() { if (stragglerInfoCase_ == 2) { return (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StreamingStragglerInfo.getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (stragglerInfoCase_ == 1) { output.writeMessage(1, (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_); } if (stragglerInfoCase_ == 2) { output.writeMessage(2, (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (stragglerInfoCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_); } if (stragglerInfoCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.dataflow.v1beta3.Straggler)) { return super.equals(obj); } com.google.dataflow.v1beta3.Straggler other = (com.google.dataflow.v1beta3.Straggler) obj; if (!getStragglerInfoCase().equals(other.getStragglerInfoCase())) return false; switch (stragglerInfoCase_) { case 1: if (!getBatchStraggler().equals(other.getBatchStraggler())) return false; break; case 2: if (!getStreamingStraggler().equals(other.getStreamingStraggler())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); switch (stragglerInfoCase_) { case 1: hash = (37 * hash) + BATCH_STRAGGLER_FIELD_NUMBER; hash = (53 * hash) + getBatchStraggler().hashCode(); break; case 2: hash = (37 * hash) + STREAMING_STRAGGLER_FIELD_NUMBER; hash = (53 * hash) + getStreamingStraggler().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.dataflow.v1beta3.Straggler parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.dataflow.v1beta3.Straggler parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.dataflow.v1beta3.Straggler parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.dataflow.v1beta3.Straggler parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.dataflow.v1beta3.Straggler parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.dataflow.v1beta3.Straggler parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.dataflow.v1beta3.Straggler parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.dataflow.v1beta3.Straggler parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.dataflow.v1beta3.Straggler parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.dataflow.v1beta3.Straggler parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.dataflow.v1beta3.Straggler parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.dataflow.v1beta3.Straggler parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.dataflow.v1beta3.Straggler prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Information for a straggler. * </pre> * * Protobuf type {@code google.dataflow.v1beta3.Straggler} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.dataflow.v1beta3.Straggler) com.google.dataflow.v1beta3.StragglerOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.dataflow.v1beta3.MetricsProto .internal_static_google_dataflow_v1beta3_Straggler_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.dataflow.v1beta3.MetricsProto .internal_static_google_dataflow_v1beta3_Straggler_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.dataflow.v1beta3.Straggler.class, com.google.dataflow.v1beta3.Straggler.Builder.class); } // Construct using com.google.dataflow.v1beta3.Straggler.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (batchStragglerBuilder_ != null) { batchStragglerBuilder_.clear(); } if (streamingStragglerBuilder_ != null) { streamingStragglerBuilder_.clear(); } stragglerInfoCase_ = 0; stragglerInfo_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.dataflow.v1beta3.MetricsProto .internal_static_google_dataflow_v1beta3_Straggler_descriptor; } @java.lang.Override public com.google.dataflow.v1beta3.Straggler getDefaultInstanceForType() { return com.google.dataflow.v1beta3.Straggler.getDefaultInstance(); } @java.lang.Override public com.google.dataflow.v1beta3.Straggler build() { com.google.dataflow.v1beta3.Straggler result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.dataflow.v1beta3.Straggler buildPartial() { com.google.dataflow.v1beta3.Straggler result = new com.google.dataflow.v1beta3.Straggler(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.dataflow.v1beta3.Straggler result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.dataflow.v1beta3.Straggler result) { result.stragglerInfoCase_ = stragglerInfoCase_; result.stragglerInfo_ = this.stragglerInfo_; if (stragglerInfoCase_ == 1 && batchStragglerBuilder_ != null) { result.stragglerInfo_ = batchStragglerBuilder_.build(); } if (stragglerInfoCase_ == 2 && streamingStragglerBuilder_ != null) { result.stragglerInfo_ = streamingStragglerBuilder_.build(); } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.dataflow.v1beta3.Straggler) { return mergeFrom((com.google.dataflow.v1beta3.Straggler) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.dataflow.v1beta3.Straggler other) { if (other == com.google.dataflow.v1beta3.Straggler.getDefaultInstance()) return this; switch (other.getStragglerInfoCase()) { case BATCH_STRAGGLER: { mergeBatchStraggler(other.getBatchStraggler()); break; } case STREAMING_STRAGGLER: { mergeStreamingStraggler(other.getStreamingStraggler()); break; } case STRAGGLERINFO_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getBatchStragglerFieldBuilder().getBuilder(), extensionRegistry); stragglerInfoCase_ = 1; break; } // case 10 case 18: { input.readMessage( getStreamingStragglerFieldBuilder().getBuilder(), extensionRegistry); stragglerInfoCase_ = 2; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int stragglerInfoCase_ = 0; private java.lang.Object stragglerInfo_; public StragglerInfoCase getStragglerInfoCase() { return StragglerInfoCase.forNumber(stragglerInfoCase_); } public Builder clearStragglerInfo() { stragglerInfoCase_ = 0; stragglerInfo_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.dataflow.v1beta3.StragglerInfo, com.google.dataflow.v1beta3.StragglerInfo.Builder, com.google.dataflow.v1beta3.StragglerInfoOrBuilder> batchStragglerBuilder_; /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> * * @return Whether the batchStraggler field is set. */ @java.lang.Override public boolean hasBatchStraggler() { return stragglerInfoCase_ == 1; } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> * * @return The batchStraggler. */ @java.lang.Override public com.google.dataflow.v1beta3.StragglerInfo getBatchStraggler() { if (batchStragglerBuilder_ == null) { if (stragglerInfoCase_ == 1) { return (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StragglerInfo.getDefaultInstance(); } else { if (stragglerInfoCase_ == 1) { return batchStragglerBuilder_.getMessage(); } return com.google.dataflow.v1beta3.StragglerInfo.getDefaultInstance(); } } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ public Builder setBatchStraggler(com.google.dataflow.v1beta3.StragglerInfo value) { if (batchStragglerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } stragglerInfo_ = value; onChanged(); } else { batchStragglerBuilder_.setMessage(value); } stragglerInfoCase_ = 1; return this; } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ public Builder setBatchStraggler( com.google.dataflow.v1beta3.StragglerInfo.Builder builderForValue) { if (batchStragglerBuilder_ == null) { stragglerInfo_ = builderForValue.build(); onChanged(); } else { batchStragglerBuilder_.setMessage(builderForValue.build()); } stragglerInfoCase_ = 1; return this; } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ public Builder mergeBatchStraggler(com.google.dataflow.v1beta3.StragglerInfo value) { if (batchStragglerBuilder_ == null) { if (stragglerInfoCase_ == 1 && stragglerInfo_ != com.google.dataflow.v1beta3.StragglerInfo.getDefaultInstance()) { stragglerInfo_ = com.google.dataflow.v1beta3.StragglerInfo.newBuilder( (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_) .mergeFrom(value) .buildPartial(); } else { stragglerInfo_ = value; } onChanged(); } else { if (stragglerInfoCase_ == 1) { batchStragglerBuilder_.mergeFrom(value); } else { batchStragglerBuilder_.setMessage(value); } } stragglerInfoCase_ = 1; return this; } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ public Builder clearBatchStraggler() { if (batchStragglerBuilder_ == null) { if (stragglerInfoCase_ == 1) { stragglerInfoCase_ = 0; stragglerInfo_ = null; onChanged(); } } else { if (stragglerInfoCase_ == 1) { stragglerInfoCase_ = 0; stragglerInfo_ = null; } batchStragglerBuilder_.clear(); } return this; } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ public com.google.dataflow.v1beta3.StragglerInfo.Builder getBatchStragglerBuilder() { return getBatchStragglerFieldBuilder().getBuilder(); } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ @java.lang.Override public com.google.dataflow.v1beta3.StragglerInfoOrBuilder getBatchStragglerOrBuilder() { if ((stragglerInfoCase_ == 1) && (batchStragglerBuilder_ != null)) { return batchStragglerBuilder_.getMessageOrBuilder(); } else { if (stragglerInfoCase_ == 1) { return (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StragglerInfo.getDefaultInstance(); } } /** * * * <pre> * Batch straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StragglerInfo batch_straggler = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.dataflow.v1beta3.StragglerInfo, com.google.dataflow.v1beta3.StragglerInfo.Builder, com.google.dataflow.v1beta3.StragglerInfoOrBuilder> getBatchStragglerFieldBuilder() { if (batchStragglerBuilder_ == null) { if (!(stragglerInfoCase_ == 1)) { stragglerInfo_ = com.google.dataflow.v1beta3.StragglerInfo.getDefaultInstance(); } batchStragglerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.dataflow.v1beta3.StragglerInfo, com.google.dataflow.v1beta3.StragglerInfo.Builder, com.google.dataflow.v1beta3.StragglerInfoOrBuilder>( (com.google.dataflow.v1beta3.StragglerInfo) stragglerInfo_, getParentForChildren(), isClean()); stragglerInfo_ = null; } stragglerInfoCase_ = 1; onChanged(); return batchStragglerBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.dataflow.v1beta3.StreamingStragglerInfo, com.google.dataflow.v1beta3.StreamingStragglerInfo.Builder, com.google.dataflow.v1beta3.StreamingStragglerInfoOrBuilder> streamingStragglerBuilder_; /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> * * @return Whether the streamingStraggler field is set. */ @java.lang.Override public boolean hasStreamingStraggler() { return stragglerInfoCase_ == 2; } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> * * @return The streamingStraggler. */ @java.lang.Override public com.google.dataflow.v1beta3.StreamingStragglerInfo getStreamingStraggler() { if (streamingStragglerBuilder_ == null) { if (stragglerInfoCase_ == 2) { return (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StreamingStragglerInfo.getDefaultInstance(); } else { if (stragglerInfoCase_ == 2) { return streamingStragglerBuilder_.getMessage(); } return com.google.dataflow.v1beta3.StreamingStragglerInfo.getDefaultInstance(); } } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ public Builder setStreamingStraggler(com.google.dataflow.v1beta3.StreamingStragglerInfo value) { if (streamingStragglerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } stragglerInfo_ = value; onChanged(); } else { streamingStragglerBuilder_.setMessage(value); } stragglerInfoCase_ = 2; return this; } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ public Builder setStreamingStraggler( com.google.dataflow.v1beta3.StreamingStragglerInfo.Builder builderForValue) { if (streamingStragglerBuilder_ == null) { stragglerInfo_ = builderForValue.build(); onChanged(); } else { streamingStragglerBuilder_.setMessage(builderForValue.build()); } stragglerInfoCase_ = 2; return this; } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ public Builder mergeStreamingStraggler( com.google.dataflow.v1beta3.StreamingStragglerInfo value) { if (streamingStragglerBuilder_ == null) { if (stragglerInfoCase_ == 2 && stragglerInfo_ != com.google.dataflow.v1beta3.StreamingStragglerInfo.getDefaultInstance()) { stragglerInfo_ = com.google.dataflow.v1beta3.StreamingStragglerInfo.newBuilder( (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_) .mergeFrom(value) .buildPartial(); } else { stragglerInfo_ = value; } onChanged(); } else { if (stragglerInfoCase_ == 2) { streamingStragglerBuilder_.mergeFrom(value); } else { streamingStragglerBuilder_.setMessage(value); } } stragglerInfoCase_ = 2; return this; } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ public Builder clearStreamingStraggler() { if (streamingStragglerBuilder_ == null) { if (stragglerInfoCase_ == 2) { stragglerInfoCase_ = 0; stragglerInfo_ = null; onChanged(); } } else { if (stragglerInfoCase_ == 2) { stragglerInfoCase_ = 0; stragglerInfo_ = null; } streamingStragglerBuilder_.clear(); } return this; } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ public com.google.dataflow.v1beta3.StreamingStragglerInfo.Builder getStreamingStragglerBuilder() { return getStreamingStragglerFieldBuilder().getBuilder(); } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ @java.lang.Override public com.google.dataflow.v1beta3.StreamingStragglerInfoOrBuilder getStreamingStragglerOrBuilder() { if ((stragglerInfoCase_ == 2) && (streamingStragglerBuilder_ != null)) { return streamingStragglerBuilder_.getMessageOrBuilder(); } else { if (stragglerInfoCase_ == 2) { return (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_; } return com.google.dataflow.v1beta3.StreamingStragglerInfo.getDefaultInstance(); } } /** * * * <pre> * Streaming straggler identification and debugging information. * </pre> * * <code>.google.dataflow.v1beta3.StreamingStragglerInfo streaming_straggler = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.dataflow.v1beta3.StreamingStragglerInfo, com.google.dataflow.v1beta3.StreamingStragglerInfo.Builder, com.google.dataflow.v1beta3.StreamingStragglerInfoOrBuilder> getStreamingStragglerFieldBuilder() { if (streamingStragglerBuilder_ == null) { if (!(stragglerInfoCase_ == 2)) { stragglerInfo_ = com.google.dataflow.v1beta3.StreamingStragglerInfo.getDefaultInstance(); } streamingStragglerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.dataflow.v1beta3.StreamingStragglerInfo, com.google.dataflow.v1beta3.StreamingStragglerInfo.Builder, com.google.dataflow.v1beta3.StreamingStragglerInfoOrBuilder>( (com.google.dataflow.v1beta3.StreamingStragglerInfo) stragglerInfo_, getParentForChildren(), isClean()); stragglerInfo_ = null; } stragglerInfoCase_ = 2; onChanged(); return streamingStragglerBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.dataflow.v1beta3.Straggler) } // @@protoc_insertion_point(class_scope:google.dataflow.v1beta3.Straggler) private static final com.google.dataflow.v1beta3.Straggler DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.dataflow.v1beta3.Straggler(); } public static com.google.dataflow.v1beta3.Straggler getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Straggler> PARSER = new com.google.protobuf.AbstractParser<Straggler>() { @java.lang.Override public Straggler parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<Straggler> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Straggler> getParserForType() { return PARSER; } @java.lang.Override public com.google.dataflow.v1beta3.Straggler getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/commons-lang
15,821
src/test/java/org/apache/commons/lang3/ClassUtilsOssFuzzTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; /** * Tests {@link ClassUtils}. */ public class ClassUtilsOssFuzzTest { /** * Tests that no StackOverflowError is thrown. * <p> * OSS-Fuzz Issue 42522972: apache-commons-text:StringSubstitutorInterpolatorFuzzer: Security exception in org.apache.commons.lang3.ClassUtils.getClass * </p> */ @Test public void testGetClassLongIllegalName() throws Exception { // Input from Commons Text clusterfuzz-testcase-StringSubstitutorInterpolatorFuzzer-5447769450741760 assertThrows(ClassNotFoundException.class, () -> ClassUtils.getClass( "ˇda´~e]W]~t$t${.ubase64encoder{con+s{.ubase64encoder{con+s~t....................................ˇˇˇˇˇˇˇˇˇˇ&${localhot:ˇˇˇˇˇˇ4ˇ..................................s${.!.${.. \\E],${conÅEEE]W€EÅE.!${.ubase64encoder{conÅEEE]W€EÅE.!${.ubase64encoder{con+s~t....................................ˇˇˇˇˇˇˇˇˇˇ&${localhot:ˇˇˇˇˇˇ-636ˇ...............................................................t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--......t]V]W€EÅE.!$${.u--}")); } /** * Tests that no StackOverflowError is thrown. */ @Test public void testGetClassLongName() throws Exception { // Input from based on the above, without illegal characters. assertThrows(ClassNotFoundException.class, () -> ClassUtils.getClass(StringUtils.repeat("a.", 5_000) + "b")); } }
googleapis/google-cloud-java
36,719
java-telcoautomation/google-cloud-telcoautomation/src/main/java/com/google/cloud/telcoautomation/v1/TelcoAutomationSettings.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.telcoautomation.v1; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListBlueprintRevisionsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListBlueprintsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListDeploymentRevisionsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListDeploymentsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListEdgeSlmsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListHydratedDeploymentsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListLocationsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListOrchestrationClustersPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.ListPublicBlueprintsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.SearchBlueprintRevisionsPagedResponse; import static com.google.cloud.telcoautomation.v1.TelcoAutomationClient.SearchDeploymentRevisionsPagedResponse; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientSettings; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.cloud.telcoautomation.v1.stub.TelcoAutomationStubSettings; import com.google.longrunning.Operation; import com.google.protobuf.Empty; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link TelcoAutomationClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (telcoautomation.googleapis.com) and default port (443) are * used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the * [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings) * of getOrchestrationCluster: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * TelcoAutomationSettings.Builder telcoAutomationSettingsBuilder = * TelcoAutomationSettings.newBuilder(); * telcoAutomationSettingsBuilder * .getOrchestrationClusterSettings() * .setRetrySettings( * telcoAutomationSettingsBuilder * .getOrchestrationClusterSettings() * .getRetrySettings() * .toBuilder() * .setInitialRetryDelayDuration(Duration.ofSeconds(1)) * .setInitialRpcTimeoutDuration(Duration.ofSeconds(5)) * .setMaxAttempts(5) * .setMaxRetryDelayDuration(Duration.ofSeconds(30)) * .setMaxRpcTimeoutDuration(Duration.ofSeconds(60)) * .setRetryDelayMultiplier(1.3) * .setRpcTimeoutMultiplier(1.5) * .setTotalTimeoutDuration(Duration.ofSeconds(300)) * .build()); * TelcoAutomationSettings telcoAutomationSettings = telcoAutomationSettingsBuilder.build(); * }</pre> * * Please refer to the [Client Side Retry * Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for * additional support in setting retries. * * <p>To configure the RetrySettings of a Long Running Operation method, create an * OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to * configure the RetrySettings for createOrchestrationCluster: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * TelcoAutomationSettings.Builder telcoAutomationSettingsBuilder = * TelcoAutomationSettings.newBuilder(); * TimedRetryAlgorithm timedRetryAlgorithm = * OperationalTimedPollAlgorithm.create( * RetrySettings.newBuilder() * .setInitialRetryDelayDuration(Duration.ofMillis(500)) * .setRetryDelayMultiplier(1.5) * .setMaxRetryDelayDuration(Duration.ofMillis(5000)) * .setTotalTimeoutDuration(Duration.ofHours(24)) * .build()); * telcoAutomationSettingsBuilder * .createClusterOperationSettings() * .setPollingAlgorithm(timedRetryAlgorithm) * .build(); * }</pre> */ @Generated("by gapic-generator-java") public class TelcoAutomationSettings extends ClientSettings<TelcoAutomationSettings> { /** Returns the object with the settings used for calls to listOrchestrationClusters. */ public PagedCallSettings< ListOrchestrationClustersRequest, ListOrchestrationClustersResponse, ListOrchestrationClustersPagedResponse> listOrchestrationClustersSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listOrchestrationClustersSettings(); } /** Returns the object with the settings used for calls to getOrchestrationCluster. */ public UnaryCallSettings<GetOrchestrationClusterRequest, OrchestrationCluster> getOrchestrationClusterSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).getOrchestrationClusterSettings(); } /** Returns the object with the settings used for calls to createOrchestrationCluster. */ public UnaryCallSettings<CreateOrchestrationClusterRequest, Operation> createOrchestrationClusterSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).createOrchestrationClusterSettings(); } /** Returns the object with the settings used for calls to createOrchestrationCluster. */ public OperationCallSettings< CreateOrchestrationClusterRequest, OrchestrationCluster, OperationMetadata> createOrchestrationClusterOperationSettings() { return ((TelcoAutomationStubSettings) getStubSettings()) .createOrchestrationClusterOperationSettings(); } /** Returns the object with the settings used for calls to deleteOrchestrationCluster. */ public UnaryCallSettings<DeleteOrchestrationClusterRequest, Operation> deleteOrchestrationClusterSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).deleteOrchestrationClusterSettings(); } /** Returns the object with the settings used for calls to deleteOrchestrationCluster. */ public OperationCallSettings<DeleteOrchestrationClusterRequest, Empty, OperationMetadata> deleteOrchestrationClusterOperationSettings() { return ((TelcoAutomationStubSettings) getStubSettings()) .deleteOrchestrationClusterOperationSettings(); } /** Returns the object with the settings used for calls to listEdgeSlms. */ public PagedCallSettings<ListEdgeSlmsRequest, ListEdgeSlmsResponse, ListEdgeSlmsPagedResponse> listEdgeSlmsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listEdgeSlmsSettings(); } /** Returns the object with the settings used for calls to getEdgeSlm. */ public UnaryCallSettings<GetEdgeSlmRequest, EdgeSlm> getEdgeSlmSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).getEdgeSlmSettings(); } /** Returns the object with the settings used for calls to createEdgeSlm. */ public UnaryCallSettings<CreateEdgeSlmRequest, Operation> createEdgeSlmSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).createEdgeSlmSettings(); } /** Returns the object with the settings used for calls to createEdgeSlm. */ public OperationCallSettings<CreateEdgeSlmRequest, EdgeSlm, OperationMetadata> createEdgeSlmOperationSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).createEdgeSlmOperationSettings(); } /** Returns the object with the settings used for calls to deleteEdgeSlm. */ public UnaryCallSettings<DeleteEdgeSlmRequest, Operation> deleteEdgeSlmSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).deleteEdgeSlmSettings(); } /** Returns the object with the settings used for calls to deleteEdgeSlm. */ public OperationCallSettings<DeleteEdgeSlmRequest, Empty, OperationMetadata> deleteEdgeSlmOperationSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).deleteEdgeSlmOperationSettings(); } /** Returns the object with the settings used for calls to createBlueprint. */ public UnaryCallSettings<CreateBlueprintRequest, Blueprint> createBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).createBlueprintSettings(); } /** Returns the object with the settings used for calls to updateBlueprint. */ public UnaryCallSettings<UpdateBlueprintRequest, Blueprint> updateBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).updateBlueprintSettings(); } /** Returns the object with the settings used for calls to getBlueprint. */ public UnaryCallSettings<GetBlueprintRequest, Blueprint> getBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).getBlueprintSettings(); } /** Returns the object with the settings used for calls to deleteBlueprint. */ public UnaryCallSettings<DeleteBlueprintRequest, Empty> deleteBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).deleteBlueprintSettings(); } /** Returns the object with the settings used for calls to listBlueprints. */ public PagedCallSettings< ListBlueprintsRequest, ListBlueprintsResponse, ListBlueprintsPagedResponse> listBlueprintsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listBlueprintsSettings(); } /** Returns the object with the settings used for calls to approveBlueprint. */ public UnaryCallSettings<ApproveBlueprintRequest, Blueprint> approveBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).approveBlueprintSettings(); } /** Returns the object with the settings used for calls to proposeBlueprint. */ public UnaryCallSettings<ProposeBlueprintRequest, Blueprint> proposeBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).proposeBlueprintSettings(); } /** Returns the object with the settings used for calls to rejectBlueprint. */ public UnaryCallSettings<RejectBlueprintRequest, Blueprint> rejectBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).rejectBlueprintSettings(); } /** Returns the object with the settings used for calls to listBlueprintRevisions. */ public PagedCallSettings< ListBlueprintRevisionsRequest, ListBlueprintRevisionsResponse, ListBlueprintRevisionsPagedResponse> listBlueprintRevisionsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listBlueprintRevisionsSettings(); } /** Returns the object with the settings used for calls to searchBlueprintRevisions. */ public PagedCallSettings< SearchBlueprintRevisionsRequest, SearchBlueprintRevisionsResponse, SearchBlueprintRevisionsPagedResponse> searchBlueprintRevisionsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).searchBlueprintRevisionsSettings(); } /** Returns the object with the settings used for calls to searchDeploymentRevisions. */ public PagedCallSettings< SearchDeploymentRevisionsRequest, SearchDeploymentRevisionsResponse, SearchDeploymentRevisionsPagedResponse> searchDeploymentRevisionsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).searchDeploymentRevisionsSettings(); } /** Returns the object with the settings used for calls to discardBlueprintChanges. */ public UnaryCallSettings<DiscardBlueprintChangesRequest, DiscardBlueprintChangesResponse> discardBlueprintChangesSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).discardBlueprintChangesSettings(); } /** Returns the object with the settings used for calls to listPublicBlueprints. */ public PagedCallSettings< ListPublicBlueprintsRequest, ListPublicBlueprintsResponse, ListPublicBlueprintsPagedResponse> listPublicBlueprintsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listPublicBlueprintsSettings(); } /** Returns the object with the settings used for calls to getPublicBlueprint. */ public UnaryCallSettings<GetPublicBlueprintRequest, PublicBlueprint> getPublicBlueprintSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).getPublicBlueprintSettings(); } /** Returns the object with the settings used for calls to createDeployment. */ public UnaryCallSettings<CreateDeploymentRequest, Deployment> createDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).createDeploymentSettings(); } /** Returns the object with the settings used for calls to updateDeployment. */ public UnaryCallSettings<UpdateDeploymentRequest, Deployment> updateDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).updateDeploymentSettings(); } /** Returns the object with the settings used for calls to getDeployment. */ public UnaryCallSettings<GetDeploymentRequest, Deployment> getDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).getDeploymentSettings(); } /** Returns the object with the settings used for calls to removeDeployment. */ public UnaryCallSettings<RemoveDeploymentRequest, Empty> removeDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).removeDeploymentSettings(); } /** Returns the object with the settings used for calls to listDeployments. */ public PagedCallSettings< ListDeploymentsRequest, ListDeploymentsResponse, ListDeploymentsPagedResponse> listDeploymentsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listDeploymentsSettings(); } /** Returns the object with the settings used for calls to listDeploymentRevisions. */ public PagedCallSettings< ListDeploymentRevisionsRequest, ListDeploymentRevisionsResponse, ListDeploymentRevisionsPagedResponse> listDeploymentRevisionsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listDeploymentRevisionsSettings(); } /** Returns the object with the settings used for calls to discardDeploymentChanges. */ public UnaryCallSettings<DiscardDeploymentChangesRequest, DiscardDeploymentChangesResponse> discardDeploymentChangesSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).discardDeploymentChangesSettings(); } /** Returns the object with the settings used for calls to applyDeployment. */ public UnaryCallSettings<ApplyDeploymentRequest, Deployment> applyDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).applyDeploymentSettings(); } /** Returns the object with the settings used for calls to computeDeploymentStatus. */ public UnaryCallSettings<ComputeDeploymentStatusRequest, ComputeDeploymentStatusResponse> computeDeploymentStatusSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).computeDeploymentStatusSettings(); } /** Returns the object with the settings used for calls to rollbackDeployment. */ public UnaryCallSettings<RollbackDeploymentRequest, Deployment> rollbackDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).rollbackDeploymentSettings(); } /** Returns the object with the settings used for calls to getHydratedDeployment. */ public UnaryCallSettings<GetHydratedDeploymentRequest, HydratedDeployment> getHydratedDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).getHydratedDeploymentSettings(); } /** Returns the object with the settings used for calls to listHydratedDeployments. */ public PagedCallSettings< ListHydratedDeploymentsRequest, ListHydratedDeploymentsResponse, ListHydratedDeploymentsPagedResponse> listHydratedDeploymentsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listHydratedDeploymentsSettings(); } /** Returns the object with the settings used for calls to updateHydratedDeployment. */ public UnaryCallSettings<UpdateHydratedDeploymentRequest, HydratedDeployment> updateHydratedDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).updateHydratedDeploymentSettings(); } /** Returns the object with the settings used for calls to applyHydratedDeployment. */ public UnaryCallSettings<ApplyHydratedDeploymentRequest, HydratedDeployment> applyHydratedDeploymentSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).applyHydratedDeploymentSettings(); } /** Returns the object with the settings used for calls to listLocations. */ public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).listLocationsSettings(); } /** Returns the object with the settings used for calls to getLocation. */ public UnaryCallSettings<GetLocationRequest, Location> getLocationSettings() { return ((TelcoAutomationStubSettings) getStubSettings()).getLocationSettings(); } public static final TelcoAutomationSettings create(TelcoAutomationStubSettings stub) throws IOException { return new TelcoAutomationSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return TelcoAutomationStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return TelcoAutomationStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return TelcoAutomationStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return TelcoAutomationStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default gRPC ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return TelcoAutomationStubSettings.defaultGrpcTransportProviderBuilder(); } /** Returns a builder for the default REST ChannelProvider for this service. */ @BetaApi public static InstantiatingHttpJsonChannelProvider.Builder defaultHttpJsonTransportProviderBuilder() { return TelcoAutomationStubSettings.defaultHttpJsonTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return TelcoAutomationStubSettings.defaultTransportChannelProvider(); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return TelcoAutomationStubSettings.defaultApiClientHeaderProviderBuilder(); } /** Returns a new gRPC builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new REST builder for this class. */ public static Builder newHttpJsonBuilder() { return Builder.createHttpJsonDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected TelcoAutomationSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for TelcoAutomationSettings. */ public static class Builder extends ClientSettings.Builder<TelcoAutomationSettings, Builder> { protected Builder() throws IOException { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(TelcoAutomationStubSettings.newBuilder(clientContext)); } protected Builder(TelcoAutomationSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(TelcoAutomationStubSettings.Builder stubSettings) { super(stubSettings); } private static Builder createDefault() { return new Builder(TelcoAutomationStubSettings.newBuilder()); } private static Builder createHttpJsonDefault() { return new Builder(TelcoAutomationStubSettings.newHttpJsonBuilder()); } public TelcoAutomationStubSettings.Builder getStubSettingsBuilder() { return ((TelcoAutomationStubSettings.Builder) getStubSettings()); } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to listOrchestrationClusters. */ public PagedCallSettings.Builder< ListOrchestrationClustersRequest, ListOrchestrationClustersResponse, ListOrchestrationClustersPagedResponse> listOrchestrationClustersSettings() { return getStubSettingsBuilder().listOrchestrationClustersSettings(); } /** Returns the builder for the settings used for calls to getOrchestrationCluster. */ public UnaryCallSettings.Builder<GetOrchestrationClusterRequest, OrchestrationCluster> getOrchestrationClusterSettings() { return getStubSettingsBuilder().getOrchestrationClusterSettings(); } /** Returns the builder for the settings used for calls to createOrchestrationCluster. */ public UnaryCallSettings.Builder<CreateOrchestrationClusterRequest, Operation> createOrchestrationClusterSettings() { return getStubSettingsBuilder().createOrchestrationClusterSettings(); } /** Returns the builder for the settings used for calls to createOrchestrationCluster. */ public OperationCallSettings.Builder< CreateOrchestrationClusterRequest, OrchestrationCluster, OperationMetadata> createOrchestrationClusterOperationSettings() { return getStubSettingsBuilder().createOrchestrationClusterOperationSettings(); } /** Returns the builder for the settings used for calls to deleteOrchestrationCluster. */ public UnaryCallSettings.Builder<DeleteOrchestrationClusterRequest, Operation> deleteOrchestrationClusterSettings() { return getStubSettingsBuilder().deleteOrchestrationClusterSettings(); } /** Returns the builder for the settings used for calls to deleteOrchestrationCluster. */ public OperationCallSettings.Builder< DeleteOrchestrationClusterRequest, Empty, OperationMetadata> deleteOrchestrationClusterOperationSettings() { return getStubSettingsBuilder().deleteOrchestrationClusterOperationSettings(); } /** Returns the builder for the settings used for calls to listEdgeSlms. */ public PagedCallSettings.Builder< ListEdgeSlmsRequest, ListEdgeSlmsResponse, ListEdgeSlmsPagedResponse> listEdgeSlmsSettings() { return getStubSettingsBuilder().listEdgeSlmsSettings(); } /** Returns the builder for the settings used for calls to getEdgeSlm. */ public UnaryCallSettings.Builder<GetEdgeSlmRequest, EdgeSlm> getEdgeSlmSettings() { return getStubSettingsBuilder().getEdgeSlmSettings(); } /** Returns the builder for the settings used for calls to createEdgeSlm. */ public UnaryCallSettings.Builder<CreateEdgeSlmRequest, Operation> createEdgeSlmSettings() { return getStubSettingsBuilder().createEdgeSlmSettings(); } /** Returns the builder for the settings used for calls to createEdgeSlm. */ public OperationCallSettings.Builder<CreateEdgeSlmRequest, EdgeSlm, OperationMetadata> createEdgeSlmOperationSettings() { return getStubSettingsBuilder().createEdgeSlmOperationSettings(); } /** Returns the builder for the settings used for calls to deleteEdgeSlm. */ public UnaryCallSettings.Builder<DeleteEdgeSlmRequest, Operation> deleteEdgeSlmSettings() { return getStubSettingsBuilder().deleteEdgeSlmSettings(); } /** Returns the builder for the settings used for calls to deleteEdgeSlm. */ public OperationCallSettings.Builder<DeleteEdgeSlmRequest, Empty, OperationMetadata> deleteEdgeSlmOperationSettings() { return getStubSettingsBuilder().deleteEdgeSlmOperationSettings(); } /** Returns the builder for the settings used for calls to createBlueprint. */ public UnaryCallSettings.Builder<CreateBlueprintRequest, Blueprint> createBlueprintSettings() { return getStubSettingsBuilder().createBlueprintSettings(); } /** Returns the builder for the settings used for calls to updateBlueprint. */ public UnaryCallSettings.Builder<UpdateBlueprintRequest, Blueprint> updateBlueprintSettings() { return getStubSettingsBuilder().updateBlueprintSettings(); } /** Returns the builder for the settings used for calls to getBlueprint. */ public UnaryCallSettings.Builder<GetBlueprintRequest, Blueprint> getBlueprintSettings() { return getStubSettingsBuilder().getBlueprintSettings(); } /** Returns the builder for the settings used for calls to deleteBlueprint. */ public UnaryCallSettings.Builder<DeleteBlueprintRequest, Empty> deleteBlueprintSettings() { return getStubSettingsBuilder().deleteBlueprintSettings(); } /** Returns the builder for the settings used for calls to listBlueprints. */ public PagedCallSettings.Builder< ListBlueprintsRequest, ListBlueprintsResponse, ListBlueprintsPagedResponse> listBlueprintsSettings() { return getStubSettingsBuilder().listBlueprintsSettings(); } /** Returns the builder for the settings used for calls to approveBlueprint. */ public UnaryCallSettings.Builder<ApproveBlueprintRequest, Blueprint> approveBlueprintSettings() { return getStubSettingsBuilder().approveBlueprintSettings(); } /** Returns the builder for the settings used for calls to proposeBlueprint. */ public UnaryCallSettings.Builder<ProposeBlueprintRequest, Blueprint> proposeBlueprintSettings() { return getStubSettingsBuilder().proposeBlueprintSettings(); } /** Returns the builder for the settings used for calls to rejectBlueprint. */ public UnaryCallSettings.Builder<RejectBlueprintRequest, Blueprint> rejectBlueprintSettings() { return getStubSettingsBuilder().rejectBlueprintSettings(); } /** Returns the builder for the settings used for calls to listBlueprintRevisions. */ public PagedCallSettings.Builder< ListBlueprintRevisionsRequest, ListBlueprintRevisionsResponse, ListBlueprintRevisionsPagedResponse> listBlueprintRevisionsSettings() { return getStubSettingsBuilder().listBlueprintRevisionsSettings(); } /** Returns the builder for the settings used for calls to searchBlueprintRevisions. */ public PagedCallSettings.Builder< SearchBlueprintRevisionsRequest, SearchBlueprintRevisionsResponse, SearchBlueprintRevisionsPagedResponse> searchBlueprintRevisionsSettings() { return getStubSettingsBuilder().searchBlueprintRevisionsSettings(); } /** Returns the builder for the settings used for calls to searchDeploymentRevisions. */ public PagedCallSettings.Builder< SearchDeploymentRevisionsRequest, SearchDeploymentRevisionsResponse, SearchDeploymentRevisionsPagedResponse> searchDeploymentRevisionsSettings() { return getStubSettingsBuilder().searchDeploymentRevisionsSettings(); } /** Returns the builder for the settings used for calls to discardBlueprintChanges. */ public UnaryCallSettings.Builder< DiscardBlueprintChangesRequest, DiscardBlueprintChangesResponse> discardBlueprintChangesSettings() { return getStubSettingsBuilder().discardBlueprintChangesSettings(); } /** Returns the builder for the settings used for calls to listPublicBlueprints. */ public PagedCallSettings.Builder< ListPublicBlueprintsRequest, ListPublicBlueprintsResponse, ListPublicBlueprintsPagedResponse> listPublicBlueprintsSettings() { return getStubSettingsBuilder().listPublicBlueprintsSettings(); } /** Returns the builder for the settings used for calls to getPublicBlueprint. */ public UnaryCallSettings.Builder<GetPublicBlueprintRequest, PublicBlueprint> getPublicBlueprintSettings() { return getStubSettingsBuilder().getPublicBlueprintSettings(); } /** Returns the builder for the settings used for calls to createDeployment. */ public UnaryCallSettings.Builder<CreateDeploymentRequest, Deployment> createDeploymentSettings() { return getStubSettingsBuilder().createDeploymentSettings(); } /** Returns the builder for the settings used for calls to updateDeployment. */ public UnaryCallSettings.Builder<UpdateDeploymentRequest, Deployment> updateDeploymentSettings() { return getStubSettingsBuilder().updateDeploymentSettings(); } /** Returns the builder for the settings used for calls to getDeployment. */ public UnaryCallSettings.Builder<GetDeploymentRequest, Deployment> getDeploymentSettings() { return getStubSettingsBuilder().getDeploymentSettings(); } /** Returns the builder for the settings used for calls to removeDeployment. */ public UnaryCallSettings.Builder<RemoveDeploymentRequest, Empty> removeDeploymentSettings() { return getStubSettingsBuilder().removeDeploymentSettings(); } /** Returns the builder for the settings used for calls to listDeployments. */ public PagedCallSettings.Builder< ListDeploymentsRequest, ListDeploymentsResponse, ListDeploymentsPagedResponse> listDeploymentsSettings() { return getStubSettingsBuilder().listDeploymentsSettings(); } /** Returns the builder for the settings used for calls to listDeploymentRevisions. */ public PagedCallSettings.Builder< ListDeploymentRevisionsRequest, ListDeploymentRevisionsResponse, ListDeploymentRevisionsPagedResponse> listDeploymentRevisionsSettings() { return getStubSettingsBuilder().listDeploymentRevisionsSettings(); } /** Returns the builder for the settings used for calls to discardDeploymentChanges. */ public UnaryCallSettings.Builder< DiscardDeploymentChangesRequest, DiscardDeploymentChangesResponse> discardDeploymentChangesSettings() { return getStubSettingsBuilder().discardDeploymentChangesSettings(); } /** Returns the builder for the settings used for calls to applyDeployment. */ public UnaryCallSettings.Builder<ApplyDeploymentRequest, Deployment> applyDeploymentSettings() { return getStubSettingsBuilder().applyDeploymentSettings(); } /** Returns the builder for the settings used for calls to computeDeploymentStatus. */ public UnaryCallSettings.Builder< ComputeDeploymentStatusRequest, ComputeDeploymentStatusResponse> computeDeploymentStatusSettings() { return getStubSettingsBuilder().computeDeploymentStatusSettings(); } /** Returns the builder for the settings used for calls to rollbackDeployment. */ public UnaryCallSettings.Builder<RollbackDeploymentRequest, Deployment> rollbackDeploymentSettings() { return getStubSettingsBuilder().rollbackDeploymentSettings(); } /** Returns the builder for the settings used for calls to getHydratedDeployment. */ public UnaryCallSettings.Builder<GetHydratedDeploymentRequest, HydratedDeployment> getHydratedDeploymentSettings() { return getStubSettingsBuilder().getHydratedDeploymentSettings(); } /** Returns the builder for the settings used for calls to listHydratedDeployments. */ public PagedCallSettings.Builder< ListHydratedDeploymentsRequest, ListHydratedDeploymentsResponse, ListHydratedDeploymentsPagedResponse> listHydratedDeploymentsSettings() { return getStubSettingsBuilder().listHydratedDeploymentsSettings(); } /** Returns the builder for the settings used for calls to updateHydratedDeployment. */ public UnaryCallSettings.Builder<UpdateHydratedDeploymentRequest, HydratedDeployment> updateHydratedDeploymentSettings() { return getStubSettingsBuilder().updateHydratedDeploymentSettings(); } /** Returns the builder for the settings used for calls to applyHydratedDeployment. */ public UnaryCallSettings.Builder<ApplyHydratedDeploymentRequest, HydratedDeployment> applyHydratedDeploymentSettings() { return getStubSettingsBuilder().applyHydratedDeploymentSettings(); } /** Returns the builder for the settings used for calls to listLocations. */ public PagedCallSettings.Builder< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return getStubSettingsBuilder().listLocationsSettings(); } /** Returns the builder for the settings used for calls to getLocation. */ public UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings() { return getStubSettingsBuilder().getLocationSettings(); } @Override public TelcoAutomationSettings build() throws IOException { return new TelcoAutomationSettings(this); } } }
apache/ozone
36,529
hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/TestOmSnapshotManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.ozone.om; import static org.apache.commons.io.file.PathUtils.copyDirectory; import static org.apache.hadoop.hdds.StringUtils.string2Bytes; import static org.apache.hadoop.hdds.utils.HAUtils.getExistingFiles; import static org.apache.hadoop.ozone.OzoneConsts.OM_CHECKPOINT_DIR; import static org.apache.hadoop.ozone.OzoneConsts.OM_DB_NAME; import static org.apache.hadoop.ozone.OzoneConsts.OM_KEY_PREFIX; import static org.apache.hadoop.ozone.OzoneConsts.OM_SNAPSHOT_CHECKPOINT_DIR; import static org.apache.hadoop.ozone.OzoneConsts.SNAPSHOT_CANDIDATE_DIR; import static org.apache.hadoop.ozone.OzoneConsts.SNAPSHOT_INFO_TABLE; import static org.apache.hadoop.ozone.om.OMDBCheckpointServlet.processFile; import static org.apache.hadoop.ozone.om.OmSnapshotManager.OM_HARDLINK_FILE; import static org.apache.hadoop.ozone.om.OmSnapshotManager.getSnapshotPath; import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.BUCKET_TABLE; import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.DIRECTORY_TABLE; import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.FILE_TABLE; import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.KEY_TABLE; import static org.apache.hadoop.ozone.om.codec.OMDBDefinition.VOLUME_TABLE; import static org.apache.hadoop.ozone.om.snapshot.OmSnapshotUtils.getINode; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.hadoop.hdds.HddsConfigKeys; import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.scm.HddsWhiteboxTestUtils; import org.apache.hadoop.hdds.utils.db.DBStore; import org.apache.hadoop.hdds.utils.db.RDBBatchOperation; import org.apache.hadoop.hdds.utils.db.RDBStore; import org.apache.hadoop.hdds.utils.db.RocksDatabase; import org.apache.hadoop.hdds.utils.db.Table; import org.apache.hadoop.hdds.utils.db.TypedTable; import org.apache.hadoop.ozone.om.exceptions.OMException; import org.apache.hadoop.ozone.om.helpers.OmBucketInfo; import org.apache.hadoop.ozone.om.helpers.OmVolumeArgs; import org.apache.hadoop.ozone.om.helpers.SnapshotInfo; import org.apache.hadoop.ozone.om.snapshot.OmSnapshotUtils; import org.apache.hadoop.util.Time; import org.apache.ozone.compaction.log.SstFileInfo; import org.apache.ozone.test.GenericTestUtils; import org.apache.ozone.test.GenericTestUtils.LogCapturer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.io.TempDir; import org.rocksdb.LiveFileMetaData; import org.slf4j.event.Level; /** * Unit test ozone snapshot manager. */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TestOmSnapshotManager { private OzoneManager om; private SnapshotChainManager snapshotChainManager; private OmMetadataManagerImpl omMetadataManager; private OmSnapshotManager omSnapshotManager; private static final String CANDIDATE_DIR_NAME = OM_DB_NAME + SNAPSHOT_CANDIDATE_DIR; private File leaderDir; private File leaderSnapDir1; private File leaderSnapDir2; private File followerSnapDir2; private File leaderCheckpointDir; private File candidateDir; private File s1File; private File f1File; @BeforeAll void init(@TempDir File tempDir) throws Exception { OzoneConfiguration configuration = new OzoneConfiguration(); configuration.set(HddsConfigKeys.OZONE_METADATA_DIRS, tempDir.toString()); // Enable filesystem snapshot feature for the test regardless of the default configuration.setBoolean(OMConfigKeys.OZONE_FILESYSTEM_SNAPSHOT_ENABLED_KEY, true); // Only allow one entry in cache so each new one causes an eviction configuration.setInt( OMConfigKeys.OZONE_OM_SNAPSHOT_CACHE_MAX_SIZE, 1); configuration.setBoolean( OMConfigKeys.OZONE_OM_SNAPSHOT_ROCKSDB_METRICS_ENABLED, false); // Allow 2 fs snapshots configuration.setInt( OMConfigKeys.OZONE_OM_FS_SNAPSHOT_MAX_LIMIT, 2); OmTestManagers omTestManagers = new OmTestManagers(configuration); om = omTestManagers.getOzoneManager(); omMetadataManager = (OmMetadataManagerImpl) om.getMetadataManager(); omSnapshotManager = om.getOmSnapshotManager(); snapshotChainManager = omMetadataManager.getSnapshotChainManager(); } @AfterAll void stop() { om.stop(); } @AfterEach void cleanup() throws IOException { Table<String, SnapshotInfo> snapshotInfoTable = omMetadataManager.getSnapshotInfoTable(); Iterator<UUID> iter = snapshotChainManager.iterator(true); while (iter.hasNext()) { UUID snapshotId = iter.next(); String snapshotInfoKey = snapshotChainManager.getTableKey(snapshotId); SnapshotInfo snapshotInfo = snapshotInfoTable.get(snapshotInfoKey); snapshotChainManager.deleteSnapshot(snapshotInfo); snapshotInfoTable.delete(snapshotInfoKey); Path snapshotYaml = Paths.get(OmSnapshotManager.getSnapshotLocalPropertyYamlPath( om.getMetadataManager(), snapshotInfo)); Files.deleteIfExists(snapshotYaml); } omSnapshotManager.invalidateCache(); } @Test public void testSnapshotFeatureFlagSafetyCheck() throws IOException { // Verify that the snapshot feature config safety check method // is returning the expected value. final TypedTable<String, SnapshotInfo> snapshotInfoTable = mock(TypedTable.class); HddsWhiteboxTestUtils.setInternalState( om.getMetadataManager(), SNAPSHOT_INFO_TABLE, snapshotInfoTable); when(snapshotInfoTable.isEmpty()).thenReturn(false); assertFalse(om.getOmSnapshotManager().canDisableFsSnapshot(om.getMetadataManager())); when(snapshotInfoTable.isEmpty()).thenReturn(true); assertTrue(om.getOmSnapshotManager().canDisableFsSnapshot(om.getMetadataManager())); } @Test public void testCloseOnEviction() throws IOException, InterruptedException, TimeoutException { GenericTestUtils.setLogLevel(RDBStore.class, Level.DEBUG); LogCapturer logCapture = LogCapturer.captureLogs(RDBStore.class); // set up db tables final TypedTable<String, OmVolumeArgs> volumeTable = mock(TypedTable.class); final TypedTable<String, OmBucketInfo> bucketTable = mock(TypedTable.class); final TypedTable<String, SnapshotInfo> snapshotInfoTable = mock(TypedTable.class); HddsWhiteboxTestUtils.setInternalState( omMetadataManager, VOLUME_TABLE, volumeTable); HddsWhiteboxTestUtils.setInternalState( omMetadataManager, BUCKET_TABLE, bucketTable); HddsWhiteboxTestUtils.setInternalState( omMetadataManager, SNAPSHOT_INFO_TABLE, snapshotInfoTable); final String volumeName = UUID.randomUUID().toString(); final String dbVolumeKey = om.getMetadataManager().getVolumeKey(volumeName); final OmVolumeArgs omVolumeArgs = OmVolumeArgs.newBuilder() .setVolume(volumeName) .setAdminName("bilbo") .setOwnerName("bilbo") .build(); when(volumeTable.get(dbVolumeKey)).thenReturn(omVolumeArgs); String bucketName = UUID.randomUUID().toString(); final String dbBucketKey = om.getMetadataManager().getBucketKey( volumeName, bucketName); final OmBucketInfo omBucketInfo = OmBucketInfo.newBuilder() .setVolumeName(volumeName) .setBucketName(bucketName) .build(); when(bucketTable.get(dbBucketKey)).thenReturn(omBucketInfo); SnapshotInfo first = createSnapshotInfo(volumeName, bucketName); SnapshotInfo second = createSnapshotInfo(volumeName, bucketName); first.setGlobalPreviousSnapshotId(null); first.setPathPreviousSnapshotId(null); second.setGlobalPreviousSnapshotId(first.getSnapshotId()); second.setPathPreviousSnapshotId(first.getSnapshotId()); when(snapshotInfoTable.get(first.getTableKey())).thenReturn(first); when(snapshotInfoTable.get(second.getTableKey())).thenReturn(second); snapshotChainManager.addSnapshot(first); snapshotChainManager.addSnapshot(second); RDBBatchOperation rdbBatchOperation = new RDBBatchOperation(); // create the first snapshot checkpoint OmSnapshotManager.createOmSnapshotCheckpoint(om.getMetadataManager(), first, rdbBatchOperation); om.getMetadataManager().getStore().commitBatchOperation(rdbBatchOperation); // retrieve it and setup store mock OmSnapshot firstSnapshot = omSnapshotManager .getActiveSnapshot(first.getVolumeName(), first.getBucketName(), first.getName()) .get(); DBStore firstSnapshotStore = mock(DBStore.class); HddsWhiteboxTestUtils.setInternalState( firstSnapshot.getMetadataManager(), "store", firstSnapshotStore); // create second snapshot checkpoint (which will be used for eviction) rdbBatchOperation = new RDBBatchOperation(); OmSnapshotManager.createOmSnapshotCheckpoint(om.getMetadataManager(), second, rdbBatchOperation); om.getMetadataManager().getStore().commitBatchOperation(rdbBatchOperation); // confirm store not yet closed verify(firstSnapshotStore, times(0)).close(); // read in second snapshot to evict first omSnapshotManager .getActiveSnapshot(second.getVolumeName(), second.getBucketName(), second.getName()); // As a workaround, invalidate all cache entries in order to trigger // instances close in this test case, since JVM GC most likely would not // have triggered and closed the instances yet at this point. omSnapshotManager.invalidateCache(); // confirm store was closed verify(firstSnapshotStore, timeout(3000).times(1)).close(); // Verify RocksDBStoreMetrics registration is skipped. String msg = "Skipped Metrics registration during RocksDB init"; GenericTestUtils.waitFor(() -> { return logCapture.getOutput().contains(msg); }, 100, 30_000); } private LiveFileMetaData createMockLiveFileMetadata(String cfname, String fileName) { LiveFileMetaData lfm = mock(LiveFileMetaData.class); when(lfm.columnFamilyName()).thenReturn(cfname.getBytes(StandardCharsets.UTF_8)); when(lfm.fileName()).thenReturn(fileName); when(lfm.smallestKey()).thenReturn(string2Bytes("k1")); when(lfm.largestKey()).thenReturn(string2Bytes("k2")); return lfm; } @Test public void testCreateNewSnapshotLocalYaml() throws IOException { SnapshotInfo snapshotInfo = createSnapshotInfo("vol1", "buck1"); Map<String, List<String>> expNotDefraggedSSTFileList = new TreeMap<>(); OmSnapshotLocalData.VersionMeta notDefraggedVersionMeta = new OmSnapshotLocalData.VersionMeta(0, ImmutableList.of(new SstFileInfo("dt1.sst", "k1", "k2", DIRECTORY_TABLE), new SstFileInfo("dt2.sst", "k1", "k2", DIRECTORY_TABLE), new SstFileInfo("ft1.sst", "k1", "k2", FILE_TABLE), new SstFileInfo("ft2.sst", "k1", "k2", FILE_TABLE), new SstFileInfo("kt1.sst", "k1", "k2", KEY_TABLE), new SstFileInfo("kt2.sst", "k1", "k2", KEY_TABLE))); expNotDefraggedSSTFileList.put(KEY_TABLE, Stream.of("kt1.sst", "kt2.sst").collect(Collectors.toList())); expNotDefraggedSSTFileList.put(FILE_TABLE, Stream.of("ft1.sst", "ft2.sst").collect(Collectors.toList())); expNotDefraggedSSTFileList.put(DIRECTORY_TABLE, Stream.of("dt1.sst", "dt2.sst").collect(Collectors.toList())); List<LiveFileMetaData> mockedLiveFiles = new ArrayList<>(); for (Map.Entry<String, List<String>> entry : expNotDefraggedSSTFileList.entrySet()) { String cfname = entry.getKey(); for (String fname : entry.getValue()) { mockedLiveFiles.add(createMockLiveFileMetadata(cfname, fname)); } } // Add some other column families and files that should be ignored mockedLiveFiles.add(createMockLiveFileMetadata("otherTable", "ot1.sst")); mockedLiveFiles.add(createMockLiveFileMetadata("otherTable", "ot2.sst")); RDBStore mockedStore = mock(RDBStore.class); RocksDatabase mockedDb = mock(RocksDatabase.class); when(mockedStore.getDb()).thenReturn(mockedDb); when(mockedDb.getLiveFilesMetaData()).thenReturn(mockedLiveFiles); Path snapshotYaml = Paths.get(OmSnapshotManager.getSnapshotLocalPropertyYamlPath( omMetadataManager, snapshotInfo)); when(mockedStore.getDbLocation()).thenReturn(getSnapshotPath(omMetadataManager, snapshotInfo).toFile()); // Create an existing YAML file for the snapshot assertTrue(snapshotYaml.toFile().createNewFile()); assertEquals(0, Files.size(snapshotYaml)); // Create a new YAML file for the snapshot OmSnapshotManager.createNewOmSnapshotLocalDataFile(omSnapshotManager, mockedStore, snapshotInfo); // Verify that previous file was overwritten assertTrue(Files.exists(snapshotYaml)); assertTrue(Files.size(snapshotYaml) > 0); // Verify the contents of the YAML file OmSnapshotLocalData localData = OmSnapshotLocalDataYaml.getFromYamlFile(omSnapshotManager, snapshotYaml.toFile()); assertNotNull(localData); assertEquals(0, localData.getVersion()); assertEquals(notDefraggedVersionMeta, localData.getVersionSstFileInfos().get(0)); assertFalse(localData.getSstFiltered()); assertEquals(0L, localData.getLastDefragTime()); assertFalse(localData.getNeedsDefrag()); assertEquals(1, localData.getVersionSstFileInfos().size()); // Cleanup Files.delete(snapshotYaml); } @Test public void testValidateSnapshotLimit() throws IOException { TypedTable<String, SnapshotInfo> snapshotInfoTable = mock(TypedTable.class); HddsWhiteboxTestUtils.setInternalState( omMetadataManager, SNAPSHOT_INFO_TABLE, snapshotInfoTable); SnapshotInfo first = createSnapshotInfo("vol1", "buck1"); SnapshotInfo second = createSnapshotInfo("vol1", "buck1"); first.setGlobalPreviousSnapshotId(null); first.setPathPreviousSnapshotId(null); second.setGlobalPreviousSnapshotId(first.getSnapshotId()); second.setPathPreviousSnapshotId(first.getSnapshotId()); when(snapshotInfoTable.get(first.getTableKey())).thenReturn(first); when(snapshotInfoTable.get(second.getTableKey())).thenReturn(second); snapshotChainManager.addSnapshot(first); assertDoesNotThrow(() -> omSnapshotManager.snapshotLimitCheck()); omSnapshotManager.decrementInFlightSnapshotCount(); snapshotChainManager.addSnapshot(second); OMException exception = assertThrows(OMException.class, () -> omSnapshotManager.snapshotLimitCheck()); assertEquals(OMException.ResultCodes.TOO_MANY_SNAPSHOTS, exception.getResult()); snapshotChainManager.deleteSnapshot(second); assertDoesNotThrow(() -> omSnapshotManager.snapshotLimitCheck()); } @BeforeEach void setupData(@TempDir File testDir) throws IOException { // Set up the leader with the following files: // leader/db.checkpoints/checkpoint1/f1.sst // leader/db.snapshots/checkpointState/snap1/s1.sst // leader/db.snapshots/checkpointState/snap2/noLink.sst // leader/db.snapshots/checkpointState/snap2/nonSstFile // Set up the follower with the following files, (as if they came // from the tarball from the leader) // follower/om.db.candidate/f1.sst // follower/om.db.candidate/db.snapshots/checkpointState/snap1/s1.sst // follower/om.db.candidate/db.snapshots/checkpointState/snap2/noLink.sst // follower/om.db.candidate/db.snapshots/checkpointState/snap2/nonSstFile // Note that the layout between leader and follower is slightly // different in that the f1.sst on the leader is in the // db.checkpoints/checkpoint1 directory but on the follower is // moved to the om.db.candidate directory; the links must be adjusted // accordingly. byte[] dummyData = {0}; // Create dummy leader files to calculate links. leaderDir = new File(testDir, "leader"); assertTrue(leaderDir.mkdirs()); String pathSnap1 = OM_SNAPSHOT_CHECKPOINT_DIR + OM_KEY_PREFIX + "snap1"; String pathSnap2 = OM_SNAPSHOT_CHECKPOINT_DIR + OM_KEY_PREFIX + "snap2"; leaderSnapDir1 = new File(leaderDir.toString(), pathSnap1); assertTrue(leaderSnapDir1.mkdirs()); Files.write(Paths.get(leaderSnapDir1.toString(), "s1.sst"), dummyData); leaderSnapDir2 = new File(leaderDir.toString(), pathSnap2); assertTrue(leaderSnapDir2.mkdirs()); Files.write(Paths.get(leaderSnapDir2.toString(), "noLink.sst"), dummyData); Files.write(Paths.get(leaderSnapDir2.toString(), "nonSstFile"), dummyData); // Also create the follower files. candidateDir = new File(testDir, CANDIDATE_DIR_NAME); File followerSnapDir1 = new File(candidateDir.toString(), pathSnap1); followerSnapDir2 = new File(candidateDir.toString(), pathSnap2); copyDirectory(leaderDir.toPath(), candidateDir.toPath()); f1File = new File(candidateDir, "f1.sst"); Files.write(f1File.toPath(), dummyData); s1File = new File(followerSnapDir1, "s1.sst"); // confirm s1 file got copied over. assertTrue(s1File.exists()); // Finish creating leaders files that are not to be copied over, because // f1.sst belongs in a different directory as explained above. leaderCheckpointDir = new File(leaderDir.toString(), OM_CHECKPOINT_DIR + OM_KEY_PREFIX + "checkpoint1"); assertTrue(leaderCheckpointDir.mkdirs()); Files.write(Paths.get(leaderCheckpointDir.toString(), "f1.sst"), dummyData); } /* * Create map of links to files on the leader: * leader/db.snapshots/checkpointState/snap2/<link to f1.sst> * leader/db.snapshots/checkpointState/snap2/<link to s1.sst> * and test that corresponding links are created on the Follower: * follower/db.snapshots/checkpointState/snap2/f1.sst * follower/db.snapshots/checkpointState/snap2/s1.sst */ @Test public void testHardLinkCreation() throws IOException { // Map of links to files on the leader Map<Path, Path> hardLinkFiles = new HashMap<>(); hardLinkFiles.put(Paths.get(leaderSnapDir2.toString(), "f1.sst"), Paths.get(leaderCheckpointDir.toString(), "f1.sst")); hardLinkFiles.put(Paths.get(leaderSnapDir2.toString(), "s1.sst"), Paths.get(leaderSnapDir1.toString(), "s1.sst")); // Create link list from leader map. Path hardLinkList = OmSnapshotUtils.createHardLinkList( leaderDir.toString().length() + 1, hardLinkFiles); Files.move(hardLinkList, Paths.get(candidateDir.toString(), OM_HARDLINK_FILE)); // Pointers to follower links to be created. File f1FileLink = new File(followerSnapDir2, "f1.sst"); File s1FileLink = new File(followerSnapDir2, "s1.sst"); // Create links on the follower from list. OmSnapshotUtils.createHardLinks(candidateDir.toPath(), false); // Confirm expected follower links. assertTrue(s1FileLink.exists()); assertEquals(getINode(s1File.toPath()), getINode(s1FileLink.toPath()), "link matches original file"); assertTrue(f1FileLink.exists()); assertEquals(getINode(f1File.toPath()), getINode(f1FileLink.toPath()), "link matches original file"); } @Test public void testGetSnapshotInfo() throws IOException { SnapshotInfo s1 = createSnapshotInfo("vol", "buck"); UUID latestGlobalSnapId = snapshotChainManager.getLatestGlobalSnapshotId(); UUID latestPathSnapId = snapshotChainManager.getLatestPathSnapshotId(String.join("/", "vol", "buck")); s1.setPathPreviousSnapshotId(latestPathSnapId); s1.setGlobalPreviousSnapshotId(latestGlobalSnapId); snapshotChainManager.addSnapshot(s1); OMException ome = assertThrows(OMException.class, () -> om.getOmSnapshotManager().getSnapshot(s1.getSnapshotId())); assertEquals(OMException.ResultCodes.FILE_NOT_FOUND, ome.getResult()); // not present in snapshot chain too SnapshotInfo s2 = createSnapshotInfo("vol", "buck"); ome = assertThrows(OMException.class, () -> om.getOmSnapshotManager().getSnapshot(s2.getSnapshotId())); assertEquals(OMException.ResultCodes.FILE_NOT_FOUND, ome.getResult()); // add to make cleanup work TypedTable<String, SnapshotInfo> snapshotInfoTable = mock(TypedTable.class); HddsWhiteboxTestUtils.setInternalState( omMetadataManager, SNAPSHOT_INFO_TABLE, snapshotInfoTable); when(snapshotInfoTable.get(s1.getTableKey())).thenReturn(s1); } /* * Test that exclude list is generated correctly. */ @Test public void testExcludeUtilities() throws IOException { File noLinkFile = new File(followerSnapDir2, "noLink.sst"); File nonSstFile = new File(followerSnapDir2, "nonSstFile"); // Confirm that the list of existing sst files is as expected. List<String> existingSstList = getExistingFiles(candidateDir); Set<String> existingSstFiles = new HashSet<>(existingSstList); Set<String> expectedSstFileNames = new HashSet<>(Arrays.asList( s1File.getName(), noLinkFile.getName(), f1File.getName(), nonSstFile.getName())); assertEquals(expectedSstFileNames, existingSstFiles); } /* * Confirm that processFile() correctly determines whether a file * should be copied, linked, or excluded from the tarball entirely. * This test always passes in a null dest dir. */ @Test void testProcessFileWithNullDestDirParameter(@TempDir File testDir) throws IOException { assertTrue(new File(testDir, "snap1").mkdirs()); assertTrue(new File(testDir, "snap2").mkdirs()); Path copyFile = Paths.get(testDir.toString(), "snap1/copyfile.sst"); Path copyFileName = copyFile.getFileName(); assertNotNull(copyFileName); Files.write(copyFile, "dummyData".getBytes(StandardCharsets.UTF_8)); long expectedFileSize = Files.size(copyFile); Path excludeFile = Paths.get(testDir.toString(), "snap1/excludeFile.sst"); Path excludeFileName = excludeFile.getFileName(); assertNotNull(excludeFileName); Files.write(excludeFile, "dummyData".getBytes(StandardCharsets.UTF_8)); Path linkToExcludedFile = Paths.get(testDir.toString(), "snap2/excludeFile.sst"); Files.createLink(linkToExcludedFile, excludeFile); Path linkToCopiedFile = Paths.get(testDir.toString(), "snap2/copyfile.sst"); Files.createLink(linkToCopiedFile, copyFile); Path addToCopiedFiles = Paths.get(testDir.toString(), "snap1/copyfile2.sst"); Files.write(addToCopiedFiles, "dummyData".getBytes(StandardCharsets.UTF_8)); Path addNonSstToCopiedFiles = Paths.get(testDir.toString(), "snap1/nonSst"); Files.write(addNonSstToCopiedFiles, "dummyData".getBytes(StandardCharsets.UTF_8)); Map<String, Map<Path, Path>> toExcludeFiles = new HashMap<>(); toExcludeFiles.computeIfAbsent(excludeFileName.toString(), (k) -> new HashMap<>()).put(excludeFile, excludeFile); Map<String, Map<Path, Path>> copyFiles = new HashMap<>(); copyFiles.computeIfAbsent(copyFileName.toString(), (k) -> new HashMap<>()).put(copyFile, copyFile); Map<Path, Path> hardLinkFiles = new HashMap<>(); long fileSize; fileSize = processFile(excludeFile, copyFiles, hardLinkFiles, toExcludeFiles, null); assertEquals(copyFiles.size(), 1); assertEquals(hardLinkFiles.size(), 0); assertEquals(fileSize, 0); // Confirm the linkToExcludedFile gets added as a link. fileSize = processFile(linkToExcludedFile, copyFiles, hardLinkFiles, toExcludeFiles, null); assertEquals(copyFiles.size(), 1); assertEquals(hardLinkFiles.size(), 1); assertEquals(hardLinkFiles.get(linkToExcludedFile), excludeFile); assertEquals(fileSize, 0); hardLinkFiles = new HashMap<>(); // Confirm the linkToCopiedFile gets added as a link. fileSize = processFile(linkToCopiedFile, copyFiles, hardLinkFiles, toExcludeFiles, null); assertEquals(copyFiles.size(), 1); assertEquals(hardLinkFiles.size(), 1); assertEquals(hardLinkFiles.get(linkToCopiedFile), copyFile); assertEquals(fileSize, 0); hardLinkFiles = new HashMap<>(); // Confirm the addToCopiedFiles gets added to list of copied files fileSize = processFile(addToCopiedFiles, copyFiles, hardLinkFiles, toExcludeFiles, null); assertEquals(copyFiles.size(), 2); assertEquals(copyFiles.get(addToCopiedFiles.getFileName().toString()).get(addToCopiedFiles), addToCopiedFiles); assertEquals(fileSize, expectedFileSize); copyFiles = new HashMap<>(); copyFiles.computeIfAbsent(copyFileName.toString(), (k) -> new HashMap<>()).put(copyFile, copyFile); // Confirm the addNonSstToCopiedFiles gets added to list of copied files fileSize = processFile(addNonSstToCopiedFiles, copyFiles, hardLinkFiles, toExcludeFiles, null); assertEquals(copyFiles.size(), 2); assertEquals(fileSize, 0); assertEquals(copyFiles.get(addNonSstToCopiedFiles.getFileName().toString()).get(addNonSstToCopiedFiles), addNonSstToCopiedFiles); } /* * Confirm that processFile() correctly determines whether a file * should be copied, linked, or excluded from the tarball entirely. * This test always passes in a non-null dest dir. */ @Test void testProcessFileWithDestDirParameter(@TempDir File testDir) throws IOException { assertTrue(new File(testDir, "snap1").mkdirs()); assertTrue(new File(testDir, "snap2").mkdirs()); assertTrue(new File(testDir, "snap3").mkdirs()); Path destDir = Paths.get(testDir.toString(), "destDir"); assertTrue(new File(destDir.toString()).mkdirs()); // Create test files. Path copyFile = Paths.get(testDir.toString(), "snap1/copyfile.sst"); Path copyFileName = copyFile.getFileName(); assertNotNull(copyFileName); Path destCopyFile = Paths.get(destDir.toString(), "snap1/copyfile.sst"); Files.write(copyFile, "dummyData".getBytes(StandardCharsets.UTF_8)); Path sameNameAsCopyFile = Paths.get(testDir.toString(), "snap3/copyFile.sst"); Files.write(sameNameAsCopyFile, "dummyData".getBytes(StandardCharsets.UTF_8)); Path destSameNameAsCopyFile = Paths.get(destDir.toString(), "snap3/copyFile.sst"); long expectedFileSize = Files.size(copyFile); Path excludeFile = Paths.get(testDir.toString(), "snap1/excludeFile.sst"); Path excludeFileName = excludeFile.getFileName(); assertNotNull(excludeFileName); Path destExcludeFile = Paths.get(destDir.toString(), "snap1/excludeFile.sst"); Files.write(excludeFile, "dummyData".getBytes(StandardCharsets.UTF_8)); Path linkToExcludedFile = Paths.get(testDir.toString(), "snap2/excludeFile.sst"); Path destLinkToExcludedFile = Paths.get(destDir.toString(), "snap2/excludeFile.sst"); Files.createLink(linkToExcludedFile, excludeFile); Path sameNameAsExcludeFile = Paths.get(testDir.toString(), "snap3/excludeFile.sst"); Files.write(sameNameAsExcludeFile, "dummyData".getBytes(StandardCharsets.UTF_8)); Path destSameNameAsExcludeFile = Paths.get(destDir.toString(), "snap3/excludeFile.sst"); Path linkToCopiedFile = Paths.get(testDir.toString(), "snap2/copyfile.sst"); Path destLinkToCopiedFile = Paths.get(destDir.toString(), "snap2/copyfile.sst"); Files.createLink(linkToCopiedFile, copyFile); Path addToCopiedFiles = Paths.get(testDir.toString(), "snap1/copyfile2.sst"); Path destAddToCopiedFiles = Paths.get(destDir.toString(), "snap1/copyfile2.sst"); Files.write(addToCopiedFiles, "dummyData".getBytes(StandardCharsets.UTF_8)); Path addNonSstToCopiedFiles = Paths.get(testDir.toString(), "snap1/nonSst"); Path destAddNonSstToCopiedFiles = Paths.get(destDir.toString(), "snap1/nonSst"); Files.write(addNonSstToCopiedFiles, "dummyData".getBytes(StandardCharsets.UTF_8)); // Create test data structures. Map<String, Map<Path, Path>> toExcludeFiles = new HashMap<>(); toExcludeFiles.put(excludeFileName.toString(), ImmutableMap.of(excludeFile, destExcludeFile)); Map<String, Map<Path, Path>> copyFiles = new HashMap<>(); copyFiles.computeIfAbsent(copyFileName.toString(), (k) -> new HashMap<>()).put(copyFile, destCopyFile); Map<Path, Path> hardLinkFiles = new HashMap<>(); long fileSize; fileSize = processFile(excludeFile, copyFiles, hardLinkFiles, toExcludeFiles, destExcludeFile.getParent()); assertEquals(copyFiles.size(), 1); assertEquals(hardLinkFiles.size(), 0); assertEquals(fileSize, 0); // Confirm the linkToExcludedFile gets added as a link. fileSize = processFile(linkToExcludedFile, copyFiles, hardLinkFiles, toExcludeFiles, destLinkToExcludedFile.getParent()); assertEquals(copyFiles.size(), 1); assertEquals(hardLinkFiles.size(), 1); assertEquals(hardLinkFiles.get(destLinkToExcludedFile), destExcludeFile); assertEquals(fileSize, 0); hardLinkFiles = new HashMap<>(); // Confirm the file with same name as excluded file gets copied. fileSize = processFile(sameNameAsExcludeFile, copyFiles, hardLinkFiles, toExcludeFiles, destSameNameAsExcludeFile.getParent()); assertEquals(copyFiles.size(), 2); assertEquals(hardLinkFiles.size(), 0); assertEquals(copyFiles.get(sameNameAsExcludeFile.getFileName().toString()).get(sameNameAsExcludeFile), destSameNameAsExcludeFile); assertEquals(fileSize, expectedFileSize); copyFiles = new HashMap<>(); copyFiles.computeIfAbsent(copyFileName.toString(), (k) -> new HashMap<>()).put(copyFile, destCopyFile); // Confirm the file with same name as copy file gets copied. fileSize = processFile(sameNameAsCopyFile, copyFiles, hardLinkFiles, toExcludeFiles, destSameNameAsCopyFile.getParent()); assertEquals(copyFiles.size(), 2); assertEquals(hardLinkFiles.size(), 0); assertEquals(copyFiles.get(sameNameAsCopyFile.getFileName().toString()).get(sameNameAsCopyFile), destSameNameAsCopyFile); assertEquals(fileSize, expectedFileSize); copyFiles = new HashMap<>(); copyFiles.computeIfAbsent(copyFileName.toString(), (k) -> new HashMap<>()).put(copyFile, destCopyFile); // Confirm the linkToCopiedFile gets added as a link. fileSize = processFile(linkToCopiedFile, copyFiles, hardLinkFiles, toExcludeFiles, destLinkToCopiedFile.getParent()); assertEquals(copyFiles.size(), 1); assertEquals(hardLinkFiles.size(), 1); assertEquals(hardLinkFiles.get(destLinkToCopiedFile), destCopyFile); assertEquals(fileSize, 0); hardLinkFiles = new HashMap<>(); // Confirm the addToCopiedFiles gets added to list of copied files fileSize = processFile(addToCopiedFiles, copyFiles, hardLinkFiles, toExcludeFiles, destAddToCopiedFiles.getParent()); assertEquals(copyFiles.size(), 2); assertEquals(copyFiles.get(addToCopiedFiles.getFileName().toString()).get(addToCopiedFiles), destAddToCopiedFiles); assertEquals(fileSize, expectedFileSize); copyFiles = new HashMap<>(); copyFiles.computeIfAbsent(copyFileName.toString(), (k) -> new HashMap<>()).put(copyFile, destCopyFile); // Confirm the addNonSstToCopiedFiles gets added to list of copied files fileSize = processFile(addNonSstToCopiedFiles, copyFiles, hardLinkFiles, toExcludeFiles, destAddNonSstToCopiedFiles.getParent()); assertEquals(copyFiles.size(), 2); assertEquals(fileSize, 0); assertEquals(copyFiles.get(addNonSstToCopiedFiles.getFileName().toString()).get(addNonSstToCopiedFiles), destAddNonSstToCopiedFiles); } @Test public void testCreateSnapshotIdempotent() throws Exception { // set up db tables LogCapturer logCapturer = LogCapturer.captureLogs(OmSnapshotManager.class); final TypedTable<String, OmVolumeArgs> volumeTable = mock(TypedTable.class); final TypedTable<String, OmBucketInfo> bucketTable = mock(TypedTable.class); final TypedTable<String, SnapshotInfo> snapshotInfoTable = mock(TypedTable.class); HddsWhiteboxTestUtils.setInternalState( om.getMetadataManager(), VOLUME_TABLE, volumeTable); HddsWhiteboxTestUtils.setInternalState( om.getMetadataManager(), BUCKET_TABLE, bucketTable); HddsWhiteboxTestUtils.setInternalState( om.getMetadataManager(), SNAPSHOT_INFO_TABLE, snapshotInfoTable); final String volumeName = UUID.randomUUID().toString(); final String dbVolumeKey = om.getMetadataManager().getVolumeKey(volumeName); final OmVolumeArgs omVolumeArgs = OmVolumeArgs.newBuilder() .setVolume(volumeName) .setAdminName("bilbo") .setOwnerName("bilbo") .build(); when(volumeTable.get(dbVolumeKey)).thenReturn(omVolumeArgs); String bucketName = UUID.randomUUID().toString(); final String dbBucketKey = om.getMetadataManager().getBucketKey( volumeName, bucketName); final OmBucketInfo omBucketInfo = OmBucketInfo.newBuilder() .setVolumeName(volumeName) .setBucketName(bucketName) .build(); when(bucketTable.get(dbBucketKey)).thenReturn(omBucketInfo); SnapshotInfo first = createSnapshotInfo(volumeName, bucketName); when(snapshotInfoTable.get(first.getTableKey())).thenReturn(first); // Create first checkpoint for the snapshot checkpoint RDBBatchOperation rdbBatchOperation = new RDBBatchOperation(); OmSnapshotManager.createOmSnapshotCheckpoint(om.getMetadataManager(), first, rdbBatchOperation); om.getMetadataManager().getStore().commitBatchOperation(rdbBatchOperation); assertThat(logCapturer.getOutput()).doesNotContain( "for snapshot " + first.getName() + " already exists."); logCapturer.clearOutput(); // Create checkpoint again for the same snapshot. rdbBatchOperation = new RDBBatchOperation(); OmSnapshotManager.createOmSnapshotCheckpoint(om.getMetadataManager(), first, rdbBatchOperation); om.getMetadataManager().getStore().commitBatchOperation(rdbBatchOperation); assertThat(logCapturer.getOutput()) .contains("for snapshot " + first.getTableKey() + " already exists."); } private SnapshotInfo createSnapshotInfo(String volumeName, String bucketName) { return SnapshotInfo.newInstance(volumeName, bucketName, UUID.randomUUID().toString(), UUID.randomUUID(), Time.now()); } }
googleapis/google-cloud-java
36,309
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListCorporaRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/visionai/v1/warehouse.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.visionai.v1; /** * * * <pre> * Request message for ListCorpora. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListCorporaRequest} */ public final class ListCorporaRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListCorporaRequest) ListCorporaRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListCorporaRequest.newBuilder() to construct. private ListCorporaRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListCorporaRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListCorporaRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListCorporaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListCorporaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListCorporaRequest.class, com.google.cloud.visionai.v1.ListCorporaRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project from which to list corpora. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The resource name of the project from which to list corpora. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Requested page size. API may return fewer results than requested. * If negative, INVALID_ARGUMENT error will be returned. * If unspecified or 0, API will pick a default size, which is 10. * If the requested page size is larger than the maximum size, API will pick * use the maximum size, which is 20. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results for the server to return. * Typically obtained via * [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] * of the previous * [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] * call. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A token identifying a page of results for the server to return. * Typically obtained via * [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] * of the previous * [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] * call. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * The filter applied to the returned corpora list. * Only the following restrictions are supported: * `type=&lt;Corpus.Type&gt;`, * `type!=&lt;Corpus.Type&gt;`. * </pre> * * <code>string filter = 5;</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * The filter applied to the returned corpora list. * Only the following restrictions are supported: * `type=&lt;Corpus.Type&gt;`, * `type!=&lt;Corpus.Type&gt;`. * </pre> * * <code>string filter = 5;</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, filter_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, filter_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.visionai.v1.ListCorporaRequest)) { return super.equals(obj); } com.google.cloud.visionai.v1.ListCorporaRequest other = (com.google.cloud.visionai.v1.ListCorporaRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListCorporaRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.visionai.v1.ListCorporaRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for ListCorpora. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListCorporaRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListCorporaRequest) com.google.cloud.visionai.v1.ListCorporaRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListCorporaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListCorporaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListCorporaRequest.class, com.google.cloud.visionai.v1.ListCorporaRequest.Builder.class); } // Construct using com.google.cloud.visionai.v1.ListCorporaRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListCorporaRequest_descriptor; } @java.lang.Override public com.google.cloud.visionai.v1.ListCorporaRequest getDefaultInstanceForType() { return com.google.cloud.visionai.v1.ListCorporaRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.visionai.v1.ListCorporaRequest build() { com.google.cloud.visionai.v1.ListCorporaRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.visionai.v1.ListCorporaRequest buildPartial() { com.google.cloud.visionai.v1.ListCorporaRequest result = new com.google.cloud.visionai.v1.ListCorporaRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.visionai.v1.ListCorporaRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.visionai.v1.ListCorporaRequest) { return mergeFrom((com.google.cloud.visionai.v1.ListCorporaRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.visionai.v1.ListCorporaRequest other) { if (other == com.google.cloud.visionai.v1.ListCorporaRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 42: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project from which to list corpora. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The resource name of the project from which to list corpora. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The resource name of the project from which to list corpora. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project from which to list corpora. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project from which to list corpora. * </pre> * * <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Requested page size. API may return fewer results than requested. * If negative, INVALID_ARGUMENT error will be returned. * If unspecified or 0, API will pick a default size, which is 10. * If the requested page size is larger than the maximum size, API will pick * use the maximum size, which is 20. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Requested page size. API may return fewer results than requested. * If negative, INVALID_ARGUMENT error will be returned. * If unspecified or 0, API will pick a default size, which is 10. * If the requested page size is larger than the maximum size, API will pick * use the maximum size, which is 20. * </pre> * * <code>int32 page_size = 2;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Requested page size. API may return fewer results than requested. * If negative, INVALID_ARGUMENT error will be returned. * If unspecified or 0, API will pick a default size, which is 10. * If the requested page size is larger than the maximum size, API will pick * use the maximum size, which is 20. * </pre> * * <code>int32 page_size = 2;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results for the server to return. * Typically obtained via * [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] * of the previous * [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] * call. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token identifying a page of results for the server to return. * Typically obtained via * [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] * of the previous * [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] * call. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token identifying a page of results for the server to return. * Typically obtained via * [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] * of the previous * [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] * call. * </pre> * * <code>string page_token = 3;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A token identifying a page of results for the server to return. * Typically obtained via * [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] * of the previous * [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] * call. * </pre> * * <code>string page_token = 3;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A token identifying a page of results for the server to return. * Typically obtained via * [ListCorporaResponse.next_page_token][google.cloud.visionai.v1.ListCorporaResponse.next_page_token] * of the previous * [Warehouse.ListCorpora][google.cloud.visionai.v1.Warehouse.ListCorpora] * call. * </pre> * * <code>string page_token = 3;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * The filter applied to the returned corpora list. * Only the following restrictions are supported: * `type=&lt;Corpus.Type&gt;`, * `type!=&lt;Corpus.Type&gt;`. * </pre> * * <code>string filter = 5;</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The filter applied to the returned corpora list. * Only the following restrictions are supported: * `type=&lt;Corpus.Type&gt;`, * `type!=&lt;Corpus.Type&gt;`. * </pre> * * <code>string filter = 5;</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The filter applied to the returned corpora list. * Only the following restrictions are supported: * `type=&lt;Corpus.Type&gt;`, * `type!=&lt;Corpus.Type&gt;`. * </pre> * * <code>string filter = 5;</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * The filter applied to the returned corpora list. * Only the following restrictions are supported: * `type=&lt;Corpus.Type&gt;`, * `type!=&lt;Corpus.Type&gt;`. * </pre> * * <code>string filter = 5;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * The filter applied to the returned corpora list. * Only the following restrictions are supported: * `type=&lt;Corpus.Type&gt;`, * `type!=&lt;Corpus.Type&gt;`. * </pre> * * <code>string filter = 5;</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ListCorporaRequest) } // @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListCorporaRequest) private static final com.google.cloud.visionai.v1.ListCorporaRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListCorporaRequest(); } public static com.google.cloud.visionai.v1.ListCorporaRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListCorporaRequest> PARSER = new com.google.protobuf.AbstractParser<ListCorporaRequest>() { @java.lang.Override public ListCorporaRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListCorporaRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListCorporaRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.visionai.v1.ListCorporaRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/logging-log4j2
36,483
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/Rfc5424Layout.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.logging.log4j.core.layout; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LoggingException; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.TlsSyslogFrame; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.Node; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.layout.internal.ExcludeChecker; import org.apache.logging.log4j.core.layout.internal.IncludeChecker; import org.apache.logging.log4j.core.layout.internal.ListChecker; import org.apache.logging.log4j.core.net.Facility; import org.apache.logging.log4j.core.net.Priority; import org.apache.logging.log4j.core.pattern.LogEventPatternConverter; import org.apache.logging.log4j.core.pattern.PatternConverter; import org.apache.logging.log4j.core.pattern.PatternFormatter; import org.apache.logging.log4j.core.pattern.PatternParser; import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; import org.apache.logging.log4j.core.util.NetUtils; import org.apache.logging.log4j.core.util.Patterns; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.MessageCollectionMessage; import org.apache.logging.log4j.message.StructuredDataCollectionMessage; import org.apache.logging.log4j.message.StructuredDataId; import org.apache.logging.log4j.message.StructuredDataMessage; import org.apache.logging.log4j.util.ProcessIdUtil; import org.apache.logging.log4j.util.StringBuilders; import org.apache.logging.log4j.util.Strings; /** * Formats a log event in accordance with RFC 5424. * * @see <a href="https://tools.ietf.org/html/rfc5424">RFC 5424</a> */ @Plugin(name = "Rfc5424Layout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true) public final class Rfc5424Layout extends AbstractStringLayout { /** * The default example enterprise number from RFC5424. */ public static final int DEFAULT_ENTERPRISE_NUMBER = 32473; /** * The default event id. */ public static final String DEFAULT_ID = "Audit"; /** * Match newlines in a platform-independent manner. */ public static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r?\\n"); /** * Match characters which require escaping. */ @Deprecated public static final Pattern PARAM_VALUE_ESCAPE_PATTERN = Pattern.compile("[\\\"\\]\\\\]"); /** * For now, avoid too restrictive OID checks to allow for easier transition */ public static final Pattern ENTERPRISE_ID_PATTERN = Pattern.compile("\\d+(\\.\\d+)*"); /** * Default MDC ID: {@value} . */ public static final String DEFAULT_MDCID = "mdc"; private static final String LF = "\n"; private static final int TWO_DIGITS = 10; private static final int THREE_DIGITS = 100; private static final int MILLIS_PER_MINUTE = 60000; private static final int MINUTES_PER_HOUR = 60; private static final String COMPONENT_KEY = "RFC5424-Converter"; private final Facility facility; private final String defaultId; private final String enterpriseNumber; private final boolean includeMdc; private final String mdcId; private final StructuredDataId mdcSdId; private final String localHostName; private final String appName; private final String messageId; private final String configName; private final String mdcPrefix; private final String eventPrefix; private final List<String> mdcExcludes; private final List<String> mdcIncludes; private final List<String> mdcRequired; private final ListChecker listChecker; private final boolean includeNewLine; private final String escapeNewLine; private final boolean useTlsMessageFormat; private long lastTimestamp = -1; private String timestamppStr; private final List<PatternFormatter> exceptionFormatters; private final Map<String, FieldFormatter> fieldFormatters; private final String procId; private Rfc5424Layout( final Configuration config, final Facility facility, final String id, final String ein, final boolean includeMDC, final boolean includeNL, final String escapeNL, final String mdcId, final String mdcPrefix, final String eventPrefix, final String appName, final String messageId, final String excludes, final String includes, final String required, final Charset charset, final String exceptionPattern, final boolean useTLSMessageFormat, final LoggerFields[] loggerFields) { super(charset); final PatternParser exceptionParser = createPatternParser(config, ThrowablePatternConverter.class); exceptionFormatters = exceptionPattern == null ? null : exceptionParser.parse(exceptionPattern); this.facility = facility; this.defaultId = id == null ? DEFAULT_ID : id; this.enterpriseNumber = ein; this.includeMdc = includeMDC; this.includeNewLine = includeNL; this.escapeNewLine = escapeNL == null ? null : Matcher.quoteReplacement(escapeNL); this.mdcId = mdcId != null ? mdcId : id == null ? DEFAULT_MDCID : id; this.mdcSdId = new StructuredDataId(this.mdcId, enterpriseNumber, null, null); this.mdcPrefix = mdcPrefix; this.eventPrefix = eventPrefix; this.appName = appName; this.messageId = messageId; this.useTlsMessageFormat = useTLSMessageFormat; this.localHostName = NetUtils.getCanonicalLocalHostname(); ListChecker checker = null; if (excludes != null) { final String[] array = excludes.split(Patterns.COMMA_SEPARATOR); if (array.length > 0) { mdcExcludes = new ArrayList<>(array.length); for (final String str : array) { mdcExcludes.add(str.trim()); } checker = new ExcludeChecker(mdcExcludes); } else { mdcExcludes = null; } } else { mdcExcludes = null; } if (includes != null) { final String[] array = includes.split(Patterns.COMMA_SEPARATOR); if (array.length > 0) { mdcIncludes = new ArrayList<>(array.length); for (final String str : array) { mdcIncludes.add(str.trim()); } checker = new IncludeChecker(mdcIncludes); } else { mdcIncludes = null; } } else { mdcIncludes = null; } if (required != null) { final String[] array = required.split(Patterns.COMMA_SEPARATOR); if (array.length > 0) { mdcRequired = new ArrayList<>(array.length); for (final String str : array) { mdcRequired.add(str.trim()); } } else { mdcRequired = null; } } else { mdcRequired = null; } this.listChecker = checker != null ? checker : ListChecker.NOOP_CHECKER; final String name = config == null ? null : config.getName(); configName = Strings.isNotEmpty(name) ? name : null; this.fieldFormatters = createFieldFormatters(loggerFields, config); this.procId = ProcessIdUtil.getProcessId(); } private Map<String, FieldFormatter> createFieldFormatters( final LoggerFields[] loggerFields, final Configuration config) { final Map<String, FieldFormatter> sdIdMap = new HashMap<>(loggerFields == null ? 0 : loggerFields.length); if (loggerFields != null) { for (final LoggerFields loggerField : loggerFields) { final StructuredDataId key = loggerField.getSdId() == null ? mdcSdId : loggerField.getSdId(); final Map<String, List<PatternFormatter>> sdParams = new HashMap<>(); final Map<String, String> fields = loggerField.getMap(); if (!fields.isEmpty()) { final PatternParser fieldParser = createPatternParser(config, null); for (final Map.Entry<String, String> entry : fields.entrySet()) { final List<PatternFormatter> formatters = fieldParser.parse(entry.getValue()); sdParams.put(entry.getKey(), formatters); } final FieldFormatter fieldFormatter = new FieldFormatter(sdParams, loggerField.getDiscardIfAllFieldsAreEmpty()); sdIdMap.put(key.toString(), fieldFormatter); } } } return sdIdMap.size() > 0 ? sdIdMap : null; } /** * Create a PatternParser. * * @param config The Configuration. * @param filterClass Filter the returned plugins after calling the plugin manager. * @return The PatternParser. */ private static PatternParser createPatternParser( final Configuration config, final Class<? extends PatternConverter> filterClass) { if (config == null) { return new PatternParser(config, PatternLayout.KEY, LogEventPatternConverter.class, filterClass); } PatternParser parser = config.getComponent(COMPONENT_KEY); if (parser == null) { parser = new PatternParser(config, PatternLayout.KEY, ThrowablePatternConverter.class); config.addComponent(COMPONENT_KEY, parser); parser = config.getComponent(COMPONENT_KEY); } return parser; } /** * Gets this Rfc5424Layout's content format. Specified by: * <ul> * <li>Key: "structured" Value: "true"</li> * <li>Key: "format" Value: "RFC5424"</li> * </ul> * * @return Map of content format keys supporting Rfc5424Layout */ @Override public Map<String, String> getContentFormat() { final Map<String, String> result = new HashMap<>(); result.put("structured", "true"); result.put("formatType", "RFC5424"); return result; } /** * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the RFC 5424 Syslog specification. * * @param event The LogEvent. * @return The RFC 5424 String representation of the LogEvent. */ @Override public String toSerializable(final LogEvent event) { final StringBuilder buf = getStringBuilder(); appendPriority(buf, event.getLevel()); appendTimestamp(buf, event.getTimeMillis()); appendSpace(buf); appendHostName(buf); appendSpace(buf); appendAppName(buf); appendSpace(buf); appendProcessId(buf); appendSpace(buf); appendMessageId(buf, event.getMessage()); appendSpace(buf); appendStructuredElements(buf, event); appendMessage(buf, event); if (useTlsMessageFormat) { return new TlsSyslogFrame(buf.toString()).toString(); } return buf.toString(); } private void appendPriority(final StringBuilder buffer, final Level logLevel) { buffer.append('<'); buffer.append(Priority.getPriority(facility, logLevel)); buffer.append(">1 "); } private void appendTimestamp(final StringBuilder buffer, final long milliseconds) { buffer.append(computeTimeStampString(milliseconds)); } private void appendSpace(final StringBuilder buffer) { buffer.append(' '); } private void appendHostName(final StringBuilder buffer) { buffer.append(localHostName); } private void appendAppName(final StringBuilder buffer) { if (appName != null) { buffer.append(appName); } else if (configName != null) { buffer.append(configName); } else { buffer.append('-'); } } private void appendProcessId(final StringBuilder buffer) { buffer.append(getProcId()); } private void appendMessageId(final StringBuilder buffer, final Message message) { final boolean isStructured = message instanceof StructuredDataMessage; final String type = isStructured ? ((StructuredDataMessage) message).getType() : null; if (type != null) { buffer.append(type); } else if (messageId != null) { buffer.append(messageId); } else { buffer.append('-'); } } private void appendMessage(final StringBuilder buffer, final LogEvent event) { final Message message = event.getMessage(); // This layout formats StructuredDataMessages instead of delegating to the Message itself. final String text = (message instanceof StructuredDataMessage || message instanceof MessageCollectionMessage) ? message.getFormat() : message.getFormattedMessage(); if (text != null && text.length() > 0) { buffer.append(' ').append(escapeNewlines(text, escapeNewLine)); } if (exceptionFormatters != null && event.getThrown() != null) { final StringBuilder exception = new StringBuilder(LF); for (final PatternFormatter formatter : exceptionFormatters) { formatter.format(event, exception); } buffer.append(escapeNewlines(exception.toString(), escapeNewLine)); } if (includeNewLine) { buffer.append(LF); } } private void appendStructuredElements(final StringBuilder buffer, final LogEvent event) { final Message message = event.getMessage(); final boolean isStructured = message instanceof StructuredDataMessage || message instanceof StructuredDataCollectionMessage; if (!isStructured && (fieldFormatters != null && fieldFormatters.isEmpty()) && !includeMdc) { buffer.append('-'); return; } final Map<String, StructuredDataElement> sdElements = new HashMap<>(); final Map<String, String> contextMap = event.getContextData().toMap(); if (mdcRequired != null) { checkRequired(contextMap); } if (fieldFormatters != null) { for (final Map.Entry<String, FieldFormatter> sdElement : fieldFormatters.entrySet()) { final String sdId = sdElement.getKey(); final StructuredDataElement elem = sdElement.getValue().format(event); sdElements.put(sdId, elem); } } if (includeMdc && contextMap.size() > 0) { final String mdcSdIdStr = mdcSdId.toString(); final StructuredDataElement union = sdElements.get(mdcSdIdStr); if (union != null) { union.union(contextMap); sdElements.put(mdcSdIdStr, union); } else { final StructuredDataElement formattedContextMap = new StructuredDataElement(contextMap, mdcPrefix, false); sdElements.put(mdcSdIdStr, formattedContextMap); } } if (isStructured) { if (message instanceof MessageCollectionMessage) { for (final StructuredDataMessage data : ((StructuredDataCollectionMessage) message)) { addStructuredData(sdElements, data); } } else { addStructuredData(sdElements, (StructuredDataMessage) message); } } if (sdElements.isEmpty()) { buffer.append('-'); return; } for (final Map.Entry<String, StructuredDataElement> entry : sdElements.entrySet()) { formatStructuredElement(entry.getKey(), entry.getValue(), buffer, listChecker); } } private void addStructuredData( final Map<String, StructuredDataElement> sdElements, final StructuredDataMessage data) { final Map<String, String> map = data.getData(); final StructuredDataId id = data.getId(); final String sdId = getId(id); if (sdElements.containsKey(sdId)) { final StructuredDataElement union = sdElements.get(id.toString()); union.union(map); sdElements.put(sdId, union); } else { final StructuredDataElement formattedData = new StructuredDataElement(map, eventPrefix, false); sdElements.put(sdId, formattedData); } } private String escapeNewlines(final String text, final String replacement) { if (null == replacement) { return text; } return NEWLINE_PATTERN.matcher(text).replaceAll(replacement); } protected String getProcId() { return procId; } protected List<String> getMdcExcludes() { return mdcExcludes; } protected List<String> getMdcIncludes() { return mdcIncludes; } private String computeTimeStampString(final long now) { long last; synchronized (this) { last = lastTimestamp; if (now == lastTimestamp) { return timestamppStr; } } final StringBuilder buffer = new StringBuilder(); final Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(now); buffer.append(Integer.toString(cal.get(Calendar.YEAR))); buffer.append('-'); pad(cal.get(Calendar.MONTH) + 1, TWO_DIGITS, buffer); buffer.append('-'); pad(cal.get(Calendar.DAY_OF_MONTH), TWO_DIGITS, buffer); buffer.append('T'); pad(cal.get(Calendar.HOUR_OF_DAY), TWO_DIGITS, buffer); buffer.append(':'); pad(cal.get(Calendar.MINUTE), TWO_DIGITS, buffer); buffer.append(':'); pad(cal.get(Calendar.SECOND), TWO_DIGITS, buffer); buffer.append('.'); pad(cal.get(Calendar.MILLISECOND), THREE_DIGITS, buffer); int tzmin = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / MILLIS_PER_MINUTE; if (tzmin == 0) { buffer.append('Z'); } else { if (tzmin < 0) { tzmin = -tzmin; buffer.append('-'); } else { buffer.append('+'); } final int tzhour = tzmin / MINUTES_PER_HOUR; tzmin -= tzhour * MINUTES_PER_HOUR; pad(tzhour, TWO_DIGITS, buffer); buffer.append(':'); pad(tzmin, TWO_DIGITS, buffer); } synchronized (this) { if (last == lastTimestamp) { lastTimestamp = now; timestamppStr = buffer.toString(); } } return buffer.toString(); } private void pad(final int val, int max, final StringBuilder buf) { while (max > 1) { if (val < max) { buf.append('0'); } max = max / TWO_DIGITS; } buf.append(Integer.toString(val)); } private void formatStructuredElement( final String id, final StructuredDataElement data, final StringBuilder sb, final ListChecker checker) { if ((id == null && defaultId == null) || data.discard()) { return; } sb.append('['); sb.append(id); if (!mdcSdId.toString().equals(id)) { appendMap(data.getPrefix(), data.getFields(), sb, ListChecker.NOOP_CHECKER); } else { appendMap(data.getPrefix(), data.getFields(), sb, checker); } sb.append(']'); } private String getId(final StructuredDataId id) { final StringBuilder sb = new StringBuilder(); if (id == null || id.getName() == null) { sb.append(defaultId); } else { sb.append(id.getName()); } String ein = id != null ? id.getEnterpriseNumber() : enterpriseNumber; if (StructuredDataId.RESERVED.equals(ein)) { ein = enterpriseNumber; } if (!StructuredDataId.RESERVED.equals(ein)) { sb.append('@').append(ein); } return sb.toString(); } private void checkRequired(final Map<String, String> map) { for (final String key : mdcRequired) { final String value = map.get(key); if (value == null) { throw new LoggingException("Required key " + key + " is missing from the " + mdcId); } } } private void appendMap( final String prefix, final Map<String, String> map, final StringBuilder sb, final ListChecker checker) { final SortedMap<String, String> sorted = new TreeMap<>(map); for (final Map.Entry<String, String> entry : sorted.entrySet()) { if (checker.check(entry.getKey()) && entry.getValue() != null) { sb.append(' '); if (prefix != null) { sb.append(prefix); } final String safeKey = escapeNewlines(escapeSDParams(entry.getKey()), escapeNewLine); final String safeValue = escapeNewlines(escapeSDParams(entry.getValue()), escapeNewLine); StringBuilders.appendKeyDqValue(sb, safeKey, safeValue); } } } private String escapeSDParams(final String value) { StringBuilder output = null; for (int i = 0; i < value.length(); i++) { final char cur = value.charAt(i); if (cur == '"' || cur == ']' || cur == '\\') { if (output == null) { output = new StringBuilder(value.substring(0, i)); } output.append("\\"); } if (output != null) { output.append(cur); } } return output != null ? output.toString() : value; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("facility=").append(facility.name()); sb.append(" appName=").append(appName); sb.append(" defaultId=").append(defaultId); sb.append(" enterpriseNumber=").append(enterpriseNumber); sb.append(" newLine=").append(includeNewLine); sb.append(" includeMDC=").append(includeMdc); sb.append(" messageId=").append(messageId); return sb.toString(); } /** * Create the RFC 5424 Layout. * * @param facility The Facility is used to try to classify the message. * @param id The default structured data id to use when formatting according to RFC 5424. * @param enterpriseNumber The IANA enterprise number. * @param includeMDC Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog * record. Defaults to "true:. * @param mdcId The id to use for the MDC Structured Data Element. * @param mdcPrefix The prefix to add to MDC key names. * @param eventPrefix The prefix to add to event key names. * @param newLine If true, a newline will be appended to the end of the syslog record. The default is false. * @param escapeNL String that should be used to replace newlines within the message text. * @param appName The value to use as the APP-NAME in the RFC 5424 syslog record. * @param msgId The default value to be used in the MSGID field of RFC 5424 syslog records. * @param excludes A comma separated list of MDC keys that should be excluded from the LogEvent. * @param includes A comma separated list of MDC keys that should be included in the FlumeEvent. * @param required A comma separated list of MDC keys that must be present in the MDC. * @param exceptionPattern The pattern for formatting exceptions. * @param useTlsMessageFormat If true the message will be formatted according to RFC 5425. * @param loggerFields Container for the KeyValuePairs containing the patterns * @param config The Configuration. Some Converters require access to the Interpolator. * @return An Rfc5424Layout. * @deprecated Use {@link Rfc5424LayoutBuilder instead} */ @Deprecated public static Rfc5424Layout createLayout( final Facility facility, final String id, final int enterpriseNumber, final boolean includeMDC, final String mdcId, final String mdcPrefix, final String eventPrefix, final boolean newLine, final String escapeNL, final String appName, final String msgId, final String excludes, String includes, final String required, final String exceptionPattern, final boolean useTlsMessageFormat, final LoggerFields[] loggerFields, final Configuration config) { if (includes != null && excludes != null) { LOGGER.error("mdcIncludes and mdcExcludes are mutually exclusive. Includes wil be ignored"); includes = null; } return newBuilder() .setConfiguration(config) .setFacility(facility) .setId(id) .setEin(String.valueOf(enterpriseNumber)) .setIncludeMDC(includeMDC) .setIncludeNL(newLine) .setEscapeNL(escapeNL) .setMdcId(mdcId) .setMdcPrefix(mdcPrefix) .setEventPrefix(eventPrefix) .setAppName(appName) .setMessageId(msgId) .setExcludes(excludes) .setIncludes(includes) .setRequired(required) .setCharset(StandardCharsets.UTF_8) .setExceptionPattern(exceptionPattern) .setUseTLSMessageFormat(useTlsMessageFormat) .setLoggerFields(loggerFields) .build(); } @PluginBuilderFactory public static Rfc5424LayoutBuilder newBuilder() { return new Rfc5424LayoutBuilder(); } public static class Rfc5424LayoutBuilder extends AbstractStringLayout.Builder<Rfc5424LayoutBuilder> implements org.apache.logging.log4j.core.util.Builder<Rfc5424Layout> { @PluginBuilderAttribute private Facility facility = Facility.LOCAL0; @PluginBuilderAttribute private String id; @PluginBuilderAttribute private String ein = String.valueOf(DEFAULT_ENTERPRISE_NUMBER); @PluginBuilderAttribute private Integer enterpriseNumber; @PluginBuilderAttribute private boolean includeMDC = true; @PluginBuilderAttribute private boolean includeNL; @PluginBuilderAttribute private String escapeNL; @PluginBuilderAttribute private String mdcId = DEFAULT_MDCID; @PluginBuilderAttribute private String mdcPrefix; @PluginBuilderAttribute private String eventPrefix; @PluginBuilderAttribute private String appName; @PluginBuilderAttribute private String messageId; @PluginBuilderAttribute private String excludes; @PluginBuilderAttribute private String includes; @PluginBuilderAttribute private String required; @PluginBuilderAttribute private String exceptionPattern; @PluginBuilderAttribute private boolean useTLSMessageFormat; @PluginElement(value = "loggerFields") private LoggerFields[] loggerFields; /** * @deprecated Since 2.24.0 use {@link #setConfiguration} instead. */ @Deprecated public Rfc5424LayoutBuilder setConfig(final Configuration config) { setConfiguration(config); return this; } public Rfc5424LayoutBuilder setFacility(final Facility facility) { this.facility = facility; return this; } public Rfc5424LayoutBuilder setId(final String id) { this.id = id; return this; } public Rfc5424LayoutBuilder setEin(final String ein) { this.ein = ein; return this; } public Rfc5424LayoutBuilder setIncludeMDC(final boolean includeMDC) { this.includeMDC = includeMDC; return this; } public Rfc5424LayoutBuilder setIncludeNL(final boolean includeNL) { this.includeNL = includeNL; return this; } public Rfc5424LayoutBuilder setEscapeNL(final String escapeNL) { this.escapeNL = escapeNL; return this; } public Rfc5424LayoutBuilder setMdcId(final String mdcId) { this.mdcId = mdcId; return this; } public Rfc5424LayoutBuilder setMdcPrefix(final String mdcPrefix) { this.mdcPrefix = mdcPrefix; return this; } public Rfc5424LayoutBuilder setEventPrefix(final String eventPrefix) { this.eventPrefix = eventPrefix; return this; } public Rfc5424LayoutBuilder setAppName(final String appName) { this.appName = appName; return this; } public Rfc5424LayoutBuilder setMessageId(final String messageId) { this.messageId = messageId; return this; } public Rfc5424LayoutBuilder setExcludes(final String excludes) { this.excludes = excludes; return this; } public Rfc5424LayoutBuilder setIncludes(String includes) { this.includes = includes; return this; } public Rfc5424LayoutBuilder setRequired(final String required) { this.required = required; return this; } // Kept for binary compatibility public Rfc5424LayoutBuilder setCharset(final Charset charset) { return super.setCharset(charset); } public Rfc5424LayoutBuilder setExceptionPattern(final String exceptionPattern) { this.exceptionPattern = exceptionPattern; return this; } public Rfc5424LayoutBuilder setUseTLSMessageFormat(final boolean useTLSMessageFormat) { this.useTLSMessageFormat = useTLSMessageFormat; return this; } public Rfc5424LayoutBuilder setLoggerFields(final LoggerFields[] loggerFields) { this.loggerFields = loggerFields; return this; } /** * @since 2.25.0 */ public Rfc5424LayoutBuilder setEnterpriseNumber(Integer enterpriseNumber) { this.enterpriseNumber = enterpriseNumber; return this; } @Override public Rfc5424Layout build() { if (includes != null && excludes != null) { LOGGER.error("mdcIncludes and mdcExcludes are mutually exclusive. Includes wil be ignored"); includes = null; } if (enterpriseNumber != null) { ein = String.valueOf(enterpriseNumber); } if (ein != null && !ENTERPRISE_ID_PATTERN.matcher(ein).matches()) { LOGGER.warn(String.format("provided EID %s is not in valid format!", ein)); return null; } final Charset charset = getCharset(); return new Rfc5424Layout( getConfiguration(), facility, id, ein, includeMDC, includeNL, escapeNL, mdcId, mdcPrefix, eventPrefix, appName, messageId, excludes, includes, required, charset != null ? charset : StandardCharsets.UTF_8, exceptionPattern, useTLSMessageFormat, loggerFields); } } private class FieldFormatter { private final Map<String, List<PatternFormatter>> delegateMap; private final boolean discardIfEmpty; public FieldFormatter(final Map<String, List<PatternFormatter>> fieldMap, final boolean discardIfEmpty) { this.discardIfEmpty = discardIfEmpty; this.delegateMap = fieldMap; } public StructuredDataElement format(final LogEvent event) { final Map<String, String> map = new HashMap<>(delegateMap.size()); for (final Map.Entry<String, List<PatternFormatter>> entry : delegateMap.entrySet()) { final StringBuilder buffer = new StringBuilder(); for (final PatternFormatter formatter : entry.getValue()) { formatter.format(event, buffer); } map.put(entry.getKey(), buffer.toString()); } return new StructuredDataElement(map, eventPrefix, discardIfEmpty); } } private class StructuredDataElement { private final Map<String, String> fields; private final boolean discardIfEmpty; private final String prefix; public StructuredDataElement( final Map<String, String> fields, final String prefix, final boolean discardIfEmpty) { this.discardIfEmpty = discardIfEmpty; this.fields = fields; this.prefix = prefix; } boolean discard() { if (discardIfEmpty == false) { return false; } boolean foundNotEmptyValue = false; for (final Map.Entry<String, String> entry : fields.entrySet()) { if (Strings.isNotEmpty(entry.getValue())) { foundNotEmptyValue = true; break; } } return !foundNotEmptyValue; } void union(final Map<String, String> addFields) { this.fields.putAll(addFields); } Map<String, String> getFields() { return this.fields; } String getPrefix() { return prefix; } } public Facility getFacility() { return facility; } public String getDefaultId() { return defaultId; } public String getEnterpriseNumber() { return enterpriseNumber; } public boolean isIncludeMdc() { return includeMdc; } public String getMdcId() { return mdcId; } // Used in tests String getLocalHostName() { return localHostName; } }
googleapis/google-cloud-java
36,173
java-vision/proto-google-cloud-vision-v1/src/main/java/com/google/cloud/vision/v1/Feature.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vision/v1/image_annotator.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.vision.v1; /** * * * <pre> * The type of Google Cloud Vision API detection to perform, and the maximum * number of results to return for that type. Multiple `Feature` objects can * be specified in the `features` list. * </pre> * * Protobuf type {@code google.cloud.vision.v1.Feature} */ public final class Feature extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vision.v1.Feature) FeatureOrBuilder { private static final long serialVersionUID = 0L; // Use Feature.newBuilder() to construct. private Feature(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Feature() { type_ = 0; model_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Feature(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1.ImageAnnotatorProto .internal_static_google_cloud_vision_v1_Feature_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1.ImageAnnotatorProto .internal_static_google_cloud_vision_v1_Feature_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1.Feature.class, com.google.cloud.vision.v1.Feature.Builder.class); } /** * * * <pre> * Type of Google Cloud Vision API feature to be extracted. * </pre> * * Protobuf enum {@code google.cloud.vision.v1.Feature.Type} */ public enum Type implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unspecified feature type. * </pre> * * <code>TYPE_UNSPECIFIED = 0;</code> */ TYPE_UNSPECIFIED(0), /** * * * <pre> * Run face detection. * </pre> * * <code>FACE_DETECTION = 1;</code> */ FACE_DETECTION(1), /** * * * <pre> * Run landmark detection. * </pre> * * <code>LANDMARK_DETECTION = 2;</code> */ LANDMARK_DETECTION(2), /** * * * <pre> * Run logo detection. * </pre> * * <code>LOGO_DETECTION = 3;</code> */ LOGO_DETECTION(3), /** * * * <pre> * Run label detection. * </pre> * * <code>LABEL_DETECTION = 4;</code> */ LABEL_DETECTION(4), /** * * * <pre> * Run text detection / optical character recognition (OCR). Text detection * is optimized for areas of text within a larger image; if the image is * a document, use `DOCUMENT_TEXT_DETECTION` instead. * </pre> * * <code>TEXT_DETECTION = 5;</code> */ TEXT_DETECTION(5), /** * * * <pre> * Run dense text document OCR. Takes precedence when both * `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present. * </pre> * * <code>DOCUMENT_TEXT_DETECTION = 11;</code> */ DOCUMENT_TEXT_DETECTION(11), /** * * * <pre> * Run Safe Search to detect potentially unsafe * or undesirable content. * </pre> * * <code>SAFE_SEARCH_DETECTION = 6;</code> */ SAFE_SEARCH_DETECTION(6), /** * * * <pre> * Compute a set of image properties, such as the * image's dominant colors. * </pre> * * <code>IMAGE_PROPERTIES = 7;</code> */ IMAGE_PROPERTIES(7), /** * * * <pre> * Run crop hints. * </pre> * * <code>CROP_HINTS = 9;</code> */ CROP_HINTS(9), /** * * * <pre> * Run web detection. * </pre> * * <code>WEB_DETECTION = 10;</code> */ WEB_DETECTION(10), /** * * * <pre> * Run Product Search. * </pre> * * <code>PRODUCT_SEARCH = 12;</code> */ PRODUCT_SEARCH(12), /** * * * <pre> * Run localizer for object detection. * </pre> * * <code>OBJECT_LOCALIZATION = 19;</code> */ OBJECT_LOCALIZATION(19), UNRECOGNIZED(-1), ; /** * * * <pre> * Unspecified feature type. * </pre> * * <code>TYPE_UNSPECIFIED = 0;</code> */ public static final int TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Run face detection. * </pre> * * <code>FACE_DETECTION = 1;</code> */ public static final int FACE_DETECTION_VALUE = 1; /** * * * <pre> * Run landmark detection. * </pre> * * <code>LANDMARK_DETECTION = 2;</code> */ public static final int LANDMARK_DETECTION_VALUE = 2; /** * * * <pre> * Run logo detection. * </pre> * * <code>LOGO_DETECTION = 3;</code> */ public static final int LOGO_DETECTION_VALUE = 3; /** * * * <pre> * Run label detection. * </pre> * * <code>LABEL_DETECTION = 4;</code> */ public static final int LABEL_DETECTION_VALUE = 4; /** * * * <pre> * Run text detection / optical character recognition (OCR). Text detection * is optimized for areas of text within a larger image; if the image is * a document, use `DOCUMENT_TEXT_DETECTION` instead. * </pre> * * <code>TEXT_DETECTION = 5;</code> */ public static final int TEXT_DETECTION_VALUE = 5; /** * * * <pre> * Run dense text document OCR. Takes precedence when both * `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present. * </pre> * * <code>DOCUMENT_TEXT_DETECTION = 11;</code> */ public static final int DOCUMENT_TEXT_DETECTION_VALUE = 11; /** * * * <pre> * Run Safe Search to detect potentially unsafe * or undesirable content. * </pre> * * <code>SAFE_SEARCH_DETECTION = 6;</code> */ public static final int SAFE_SEARCH_DETECTION_VALUE = 6; /** * * * <pre> * Compute a set of image properties, such as the * image's dominant colors. * </pre> * * <code>IMAGE_PROPERTIES = 7;</code> */ public static final int IMAGE_PROPERTIES_VALUE = 7; /** * * * <pre> * Run crop hints. * </pre> * * <code>CROP_HINTS = 9;</code> */ public static final int CROP_HINTS_VALUE = 9; /** * * * <pre> * Run web detection. * </pre> * * <code>WEB_DETECTION = 10;</code> */ public static final int WEB_DETECTION_VALUE = 10; /** * * * <pre> * Run Product Search. * </pre> * * <code>PRODUCT_SEARCH = 12;</code> */ public static final int PRODUCT_SEARCH_VALUE = 12; /** * * * <pre> * Run localizer for object detection. * </pre> * * <code>OBJECT_LOCALIZATION = 19;</code> */ public static final int OBJECT_LOCALIZATION_VALUE = 19; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Type valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static Type forNumber(int value) { switch (value) { case 0: return TYPE_UNSPECIFIED; case 1: return FACE_DETECTION; case 2: return LANDMARK_DETECTION; case 3: return LOGO_DETECTION; case 4: return LABEL_DETECTION; case 5: return TEXT_DETECTION; case 11: return DOCUMENT_TEXT_DETECTION; case 6: return SAFE_SEARCH_DETECTION; case 7: return IMAGE_PROPERTIES; case 9: return CROP_HINTS; case 10: return WEB_DETECTION; case 12: return PRODUCT_SEARCH; case 19: return OBJECT_LOCALIZATION; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { public Type findValueByNumber(int number) { return Type.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.vision.v1.Feature.getDescriptor().getEnumTypes().get(0); } private static final Type[] VALUES = values(); public static Type valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private Type(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.vision.v1.Feature.Type) } public static final int TYPE_FIELD_NUMBER = 1; private int type_ = 0; /** * * * <pre> * The feature type. * </pre> * * <code>.google.cloud.vision.v1.Feature.Type type = 1;</code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * The feature type. * </pre> * * <code>.google.cloud.vision.v1.Feature.Type type = 1;</code> * * @return The type. */ @java.lang.Override public com.google.cloud.vision.v1.Feature.Type getType() { com.google.cloud.vision.v1.Feature.Type result = com.google.cloud.vision.v1.Feature.Type.forNumber(type_); return result == null ? com.google.cloud.vision.v1.Feature.Type.UNRECOGNIZED : result; } public static final int MAX_RESULTS_FIELD_NUMBER = 2; private int maxResults_ = 0; /** * * * <pre> * Maximum number of results of this type. Does not apply to * `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. * </pre> * * <code>int32 max_results = 2;</code> * * @return The maxResults. */ @java.lang.Override public int getMaxResults() { return maxResults_; } public static final int MODEL_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object model_ = ""; /** * * * <pre> * Model to use for the feature. * Supported values: "builtin/stable" (the default if unset) and * "builtin/latest". `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` also * support "builtin/weekly" for the bleeding edge release updated weekly. * </pre> * * <code>string model = 3;</code> * * @return The model. */ @java.lang.Override public java.lang.String getModel() { java.lang.Object ref = model_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); model_ = s; return s; } } /** * * * <pre> * Model to use for the feature. * Supported values: "builtin/stable" (the default if unset) and * "builtin/latest". `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` also * support "builtin/weekly" for the bleeding edge release updated weekly. * </pre> * * <code>string model = 3;</code> * * @return The bytes for model. */ @java.lang.Override public com.google.protobuf.ByteString getModelBytes() { java.lang.Object ref = model_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); model_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (type_ != com.google.cloud.vision.v1.Feature.Type.TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(1, type_); } if (maxResults_ != 0) { output.writeInt32(2, maxResults_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(model_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, model_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (type_ != com.google.cloud.vision.v1.Feature.Type.TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, type_); } if (maxResults_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, maxResults_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(model_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, model_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.vision.v1.Feature)) { return super.equals(obj); } com.google.cloud.vision.v1.Feature other = (com.google.cloud.vision.v1.Feature) obj; if (type_ != other.type_) return false; if (getMaxResults() != other.getMaxResults()) return false; if (!getModel().equals(other.getModel())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (37 * hash) + MAX_RESULTS_FIELD_NUMBER; hash = (53 * hash) + getMaxResults(); hash = (37 * hash) + MODEL_FIELD_NUMBER; hash = (53 * hash) + getModel().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.vision.v1.Feature parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1.Feature parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1.Feature parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1.Feature parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1.Feature parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1.Feature parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1.Feature parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1.Feature parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1.Feature parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vision.v1.Feature parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1.Feature parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1.Feature parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.vision.v1.Feature prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The type of Google Cloud Vision API detection to perform, and the maximum * number of results to return for that type. Multiple `Feature` objects can * be specified in the `features` list. * </pre> * * Protobuf type {@code google.cloud.vision.v1.Feature} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vision.v1.Feature) com.google.cloud.vision.v1.FeatureOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1.ImageAnnotatorProto .internal_static_google_cloud_vision_v1_Feature_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1.ImageAnnotatorProto .internal_static_google_cloud_vision_v1_Feature_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1.Feature.class, com.google.cloud.vision.v1.Feature.Builder.class); } // Construct using com.google.cloud.vision.v1.Feature.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; type_ = 0; maxResults_ = 0; model_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vision.v1.ImageAnnotatorProto .internal_static_google_cloud_vision_v1_Feature_descriptor; } @java.lang.Override public com.google.cloud.vision.v1.Feature getDefaultInstanceForType() { return com.google.cloud.vision.v1.Feature.getDefaultInstance(); } @java.lang.Override public com.google.cloud.vision.v1.Feature build() { com.google.cloud.vision.v1.Feature result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vision.v1.Feature buildPartial() { com.google.cloud.vision.v1.Feature result = new com.google.cloud.vision.v1.Feature(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.vision.v1.Feature result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.type_ = type_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.maxResults_ = maxResults_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.model_ = model_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.vision.v1.Feature) { return mergeFrom((com.google.cloud.vision.v1.Feature) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.vision.v1.Feature other) { if (other == com.google.cloud.vision.v1.Feature.getDefaultInstance()) return this; if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (other.getMaxResults() != 0) { setMaxResults(other.getMaxResults()); } if (!other.getModel().isEmpty()) { model_ = other.model_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { type_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { maxResults_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { model_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int type_ = 0; /** * * * <pre> * The feature type. * </pre> * * <code>.google.cloud.vision.v1.Feature.Type type = 1;</code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * The feature type. * </pre> * * <code>.google.cloud.vision.v1.Feature.Type type = 1;</code> * * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setTypeValue(int value) { type_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The feature type. * </pre> * * <code>.google.cloud.vision.v1.Feature.Type type = 1;</code> * * @return The type. */ @java.lang.Override public com.google.cloud.vision.v1.Feature.Type getType() { com.google.cloud.vision.v1.Feature.Type result = com.google.cloud.vision.v1.Feature.Type.forNumber(type_); return result == null ? com.google.cloud.vision.v1.Feature.Type.UNRECOGNIZED : result; } /** * * * <pre> * The feature type. * </pre> * * <code>.google.cloud.vision.v1.Feature.Type type = 1;</code> * * @param value The type to set. * @return This builder for chaining. */ public Builder setType(com.google.cloud.vision.v1.Feature.Type value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; type_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * The feature type. * </pre> * * <code>.google.cloud.vision.v1.Feature.Type type = 1;</code> * * @return This builder for chaining. */ public Builder clearType() { bitField0_ = (bitField0_ & ~0x00000001); type_ = 0; onChanged(); return this; } private int maxResults_; /** * * * <pre> * Maximum number of results of this type. Does not apply to * `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. * </pre> * * <code>int32 max_results = 2;</code> * * @return The maxResults. */ @java.lang.Override public int getMaxResults() { return maxResults_; } /** * * * <pre> * Maximum number of results of this type. Does not apply to * `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. * </pre> * * <code>int32 max_results = 2;</code> * * @param value The maxResults to set. * @return This builder for chaining. */ public Builder setMaxResults(int value) { maxResults_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Maximum number of results of this type. Does not apply to * `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. * </pre> * * <code>int32 max_results = 2;</code> * * @return This builder for chaining. */ public Builder clearMaxResults() { bitField0_ = (bitField0_ & ~0x00000002); maxResults_ = 0; onChanged(); return this; } private java.lang.Object model_ = ""; /** * * * <pre> * Model to use for the feature. * Supported values: "builtin/stable" (the default if unset) and * "builtin/latest". `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` also * support "builtin/weekly" for the bleeding edge release updated weekly. * </pre> * * <code>string model = 3;</code> * * @return The model. */ public java.lang.String getModel() { java.lang.Object ref = model_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); model_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Model to use for the feature. * Supported values: "builtin/stable" (the default if unset) and * "builtin/latest". `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` also * support "builtin/weekly" for the bleeding edge release updated weekly. * </pre> * * <code>string model = 3;</code> * * @return The bytes for model. */ public com.google.protobuf.ByteString getModelBytes() { java.lang.Object ref = model_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); model_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Model to use for the feature. * Supported values: "builtin/stable" (the default if unset) and * "builtin/latest". `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` also * support "builtin/weekly" for the bleeding edge release updated weekly. * </pre> * * <code>string model = 3;</code> * * @param value The model to set. * @return This builder for chaining. */ public Builder setModel(java.lang.String value) { if (value == null) { throw new NullPointerException(); } model_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Model to use for the feature. * Supported values: "builtin/stable" (the default if unset) and * "builtin/latest". `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` also * support "builtin/weekly" for the bleeding edge release updated weekly. * </pre> * * <code>string model = 3;</code> * * @return This builder for chaining. */ public Builder clearModel() { model_ = getDefaultInstance().getModel(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Model to use for the feature. * Supported values: "builtin/stable" (the default if unset) and * "builtin/latest". `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` also * support "builtin/weekly" for the bleeding edge release updated weekly. * </pre> * * <code>string model = 3;</code> * * @param value The bytes for model to set. * @return This builder for chaining. */ public Builder setModelBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); model_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.vision.v1.Feature) } // @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Feature) private static final com.google.cloud.vision.v1.Feature DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vision.v1.Feature(); } public static com.google.cloud.vision.v1.Feature getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Feature> PARSER = new com.google.protobuf.AbstractParser<Feature>() { @java.lang.Override public Feature parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<Feature> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Feature> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vision.v1.Feature getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
36,580
jdk/src/macosx/classes/com/apple/laf/AquaInternalFrameUI.java
/* * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.apple.laf; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.MouseInputAdapter; import javax.swing.plaf.*; import javax.swing.plaf.basic.BasicInternalFrameUI; import apple.laf.*; import apple.laf.JRSUIConstants.*; import com.apple.laf.AquaUtils.*; import com.apple.laf.AquaUtils.Painter; import sun.lwawt.macosx.CPlatformWindow; /** * From AquaInternalFrameUI * * InternalFrame implementation for Aqua LAF * * We want to inherit most of the inner classes, but not the base class, * so be very careful about subclassing so you know you get what you want * */ public class AquaInternalFrameUI extends BasicInternalFrameUI implements SwingConstants { protected static final String IS_PALETTE_PROPERTY = "JInternalFrame.isPalette"; private static final String FRAME_TYPE = "JInternalFrame.frameType"; private static final String NORMAL_FRAME = "normal"; private static final String PALETTE_FRAME = "palette"; private static final String OPTION_DIALOG = "optionDialog"; // Instance variables PropertyChangeListener fPropertyListener; protected Color fSelectedTextColor; protected Color fNotSelectedTextColor; AquaInternalFrameBorder fAquaBorder; // for button tracking boolean fMouseOverPressedButton; int fWhichButtonPressed = -1; boolean fRollover = false; boolean fDocumentEdited = false; // to indicate whether we should use the dirty document red dot. boolean fIsPallet; public int getWhichButtonPressed() { return fWhichButtonPressed; } public boolean getMouseOverPressedButton() { return fMouseOverPressedButton; } public boolean getRollover() { return fRollover; } // ComponentUI Interface Implementation methods public static ComponentUI createUI(final JComponent b) { return new AquaInternalFrameUI((JInternalFrame)b); } public AquaInternalFrameUI(final JInternalFrame b) { super(b); } /// Inherit (but be careful to check everything they call): public void installUI(final JComponent c) { // super.installUI(c); // Swing 1.1.1 has a bug in installUI - it doesn't check for null northPane frame = (JInternalFrame)c; frame.add(frame.getRootPane(), "Center"); installDefaults(); installListeners(); installComponents(); installKeyboardActions(); Object paletteProp = c.getClientProperty(IS_PALETTE_PROPERTY); if (paletteProp != null) { setPalette(((Boolean)paletteProp).booleanValue()); } else { paletteProp = c.getClientProperty(FRAME_TYPE); if (paletteProp != null) { setFrameType((String)paletteProp); } else { setFrameType(NORMAL_FRAME); } } // We only have a southPane, for grow box room, created in setFrameType frame.setMinimumSize(new Dimension(fIsPallet ? 120 : 150, fIsPallet ? 39 : 65)); frame.setOpaque(false); c.setBorder(new CompoundUIBorder(fIsPallet ? paletteWindowShadow.get() : documentWindowShadow.get(), c.getBorder())); } protected void installDefaults() { super.installDefaults(); fSelectedTextColor = UIManager.getColor("InternalFrame.activeTitleForeground"); fNotSelectedTextColor = UIManager.getColor("InternalFrame.inactiveTitleForeground"); } public void setSouthPane(final JComponent c) { if (southPane != null) { frame.remove(southPane); deinstallMouseHandlers(southPane); } if (c != null) { frame.add(c); installMouseHandlers(c); } southPane = c; } static final RecyclableSingleton<Icon> closeIcon = new RecyclableSingleton<Icon>() { protected Icon getInstance() { return new AquaInternalFrameButtonIcon(Widget.TITLE_BAR_CLOSE_BOX); } }; public static Icon exportCloseIcon() { return closeIcon.get(); } static final RecyclableSingleton<Icon> minimizeIcon = new RecyclableSingleton<Icon>() { protected Icon getInstance() { return new AquaInternalFrameButtonIcon(Widget.TITLE_BAR_COLLAPSE_BOX); } }; public static Icon exportMinimizeIcon() { return minimizeIcon.get(); } static final RecyclableSingleton<Icon> zoomIcon = new RecyclableSingleton<Icon>() { protected Icon getInstance() { return new AquaInternalFrameButtonIcon(Widget.TITLE_BAR_ZOOM_BOX); } }; public static Icon exportZoomIcon() { return zoomIcon.get(); } static class AquaInternalFrameButtonIcon extends AquaIcon.JRSUIIcon { public AquaInternalFrameButtonIcon(final Widget widget) { painter.state.set(widget); } public void paintIcon(final Component c, final Graphics g, final int x, final int y) { painter.state.set(getStateFor(c)); super.paintIcon(c, g, x, y); } State getStateFor(final Component c) { return State.ROLLOVER; } public int getIconWidth() { return 19; } public int getIconHeight() { return 19; } } protected void installKeyboardActions() { } //$ Not Mac-ish - should we support? protected ResizeBox resizeBox; protected void installComponents() { final JLayeredPane layeredPane = frame.getLayeredPane(); if (resizeBox != null) { resizeBox.removeListeners(); layeredPane.removeComponentListener(resizeBox); layeredPane.remove(resizeBox); resizeBox = null; } resizeBox = new ResizeBox(layeredPane); resizeBox.repositionResizeBox(); layeredPane.add(resizeBox); layeredPane.setLayer(resizeBox, JLayeredPane.DRAG_LAYER); layeredPane.addComponentListener(resizeBox); resizeBox.addListeners(); resizeBox.setVisible(frame.isResizable()); } /// Inherit all the listeners - that's the main reason we subclass Basic! protected void installListeners() { fPropertyListener = new PropertyListener(); frame.addPropertyChangeListener(fPropertyListener); super.installListeners(); } // uninstallDefaults // uninstallComponents protected void uninstallListeners() { super.uninstallListeners(); frame.removePropertyChangeListener(fPropertyListener); } protected void uninstallKeyboardActions() { } // Called when a DesktopIcon replaces an InternalFrame & vice versa //protected void replacePane(JComponent currentPane, JComponent newPane) {} protected void installMouseHandlers(final JComponent c) { c.addMouseListener(borderListener); c.addMouseMotionListener(borderListener); } protected void deinstallMouseHandlers(final JComponent c) { c.removeMouseListener(borderListener); c.removeMouseMotionListener(borderListener); } ActionMap createActionMap() { final ActionMap map = new ActionMapUIResource(); // add action for the system menu // Set the ActionMap's parent to the Auditory Feedback Action Map final AquaLookAndFeel lf = (AquaLookAndFeel)UIManager.getLookAndFeel(); final ActionMap audioMap = lf.getAudioActionMap(); map.setParent(audioMap); return map; } public Dimension getPreferredSize(JComponent x) { Dimension preferredSize = super.getPreferredSize(x); Dimension minimumSize = frame.getMinimumSize(); if (preferredSize.width < minimumSize.width) { preferredSize.width = minimumSize.width; } if (preferredSize.height < minimumSize.height) { preferredSize.height = minimumSize.height; } return preferredSize; } public void setNorthPane(final JComponent c) { replacePane(northPane, c); northPane = c; } /** * Installs necessary mouse handlers on <code>newPane</code> * and adds it to the frame. * Reverse process for the <code>currentPane</code>. */ protected void replacePane(final JComponent currentPane, final JComponent newPane) { if (currentPane != null) { deinstallMouseHandlers(currentPane); frame.remove(currentPane); } if (newPane != null) { frame.add(newPane); installMouseHandlers(newPane); } } // Our "Border" listener is shared by the AquaDesktopIcon protected MouseInputAdapter createBorderListener(final JInternalFrame w) { return new AquaBorderListener(); } /** * Mac-specific stuff begins here */ void setFrameType(final String frameType) { // Basic sets the background of the contentPane to null so it can inherit JInternalFrame.setBackground // but if *that's* null, we get the JDesktop, which makes ours look invisible! // So JInternalFrame has to have a background color // See Sun bugs 4268949 & 4320889 final Color bg = frame.getBackground(); final boolean replaceColor = (bg == null || bg instanceof UIResource); final Font font = frame.getFont(); final boolean replaceFont = (font == null || font instanceof UIResource); boolean isPalette = false; if (frameType.equals(OPTION_DIALOG)) { fAquaBorder = AquaInternalFrameBorder.dialog(); if (replaceColor) frame.setBackground(UIManager.getColor("InternalFrame.optionDialogBackground")); if (replaceFont) frame.setFont(UIManager.getFont("InternalFrame.optionDialogTitleFont")); } else if (frameType.equals(PALETTE_FRAME)) { fAquaBorder = AquaInternalFrameBorder.utility(); if (replaceColor) frame.setBackground(UIManager.getColor("InternalFrame.paletteBackground")); if (replaceFont) frame.setFont(UIManager.getFont("InternalFrame.paletteTitleFont")); isPalette = true; } else { fAquaBorder = AquaInternalFrameBorder.window(); if (replaceColor) frame.setBackground(UIManager.getColor("InternalFrame.background")); if (replaceFont) frame.setFont(UIManager.getFont("InternalFrame.titleFont")); } // We don't get the borders from UIManager, in case someone changes them - this class will not work with // different borders. If they want different ones, they have to make their own InternalFrameUI class fAquaBorder.setColors(fSelectedTextColor, fNotSelectedTextColor); frame.setBorder(fAquaBorder); fIsPallet = isPalette; } public void setPalette(final boolean isPalette) { setFrameType(isPalette ? PALETTE_FRAME : NORMAL_FRAME); } public boolean isDocumentEdited() { return fDocumentEdited; } public void setDocumentEdited(final boolean flag) { fDocumentEdited = flag; } /* // helpful debug drawing, shows component and content bounds public void paint(final Graphics g, final JComponent c) { super.paint(g, c); g.setColor(Color.green); g.drawRect(0, 0, frame.getWidth() - 1, frame.getHeight() - 1); final Insets insets = frame.getInsets(); g.setColor(Color.orange); g.drawRect(insets.left - 2, insets.top - 2, frame.getWidth() - insets.left - insets.right + 4, frame.getHeight() - insets.top - insets.bottom + 4); } */ // Border Listener Class /** * Listens for border adjustments. */ protected class AquaBorderListener extends MouseInputAdapter { // _x & _y are the mousePressed location in absolute coordinate system int _x, _y; // __x & __y are the mousePressed location in source view's coordinate system int __x, __y; Rectangle startingBounds; boolean fDraggingFrame; int resizeDir; protected final int RESIZE_NONE = 0; private boolean discardRelease = false; public void mouseClicked(final MouseEvent e) { if (didForwardEvent(e)) return; if (e.getClickCount() <= 1 || e.getSource() != getNorthPane()) return; if (frame.isIconifiable() && frame.isIcon()) { try { frame.setIcon(false); } catch(final PropertyVetoException e2) {} } else if (frame.isMaximizable()) { if (!frame.isMaximum()) try { frame.setMaximum(true); } catch(final PropertyVetoException e2) {} else try { frame.setMaximum(false); } catch(final PropertyVetoException e3) {} } } public void updateRollover(final MouseEvent e) { final boolean oldRollover = fRollover; final Insets i = frame.getInsets(); fRollover = (isTitleBarDraggableArea(e) && fAquaBorder.getWithinRolloverArea(i, e.getX(), e.getY())); if (fRollover != oldRollover) { repaintButtons(); } } public void repaintButtons() { fAquaBorder.repaintButtonArea(frame); } public void mouseReleased(final MouseEvent e) { if (didForwardEvent(e)) return; fDraggingFrame = false; if (fWhichButtonPressed != -1) { final int newButton = fAquaBorder.getWhichButtonHit(frame, e.getX(), e.getY()); final int buttonPresed = fWhichButtonPressed; fWhichButtonPressed = -1; fMouseOverPressedButton = false; if (buttonPresed == newButton) { fMouseOverPressedButton = false; fRollover = false; // not sure if this is needed? fAquaBorder.doButtonAction(frame, buttonPresed); } updateRollover(e); repaintButtons(); return; } if (discardRelease) { discardRelease = false; return; } if (resizeDir == RESIZE_NONE) getDesktopManager().endDraggingFrame(frame); else { final Container c = frame.getTopLevelAncestor(); if (c instanceof JFrame) { ((JFrame)frame.getTopLevelAncestor()).getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); ((JFrame)frame.getTopLevelAncestor()).getGlassPane().setVisible(false); } else if (c instanceof JApplet) { ((JApplet)c).getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); ((JApplet)c).getGlassPane().setVisible(false); } else if (c instanceof JWindow) { ((JWindow)c).getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); ((JWindow)c).getGlassPane().setVisible(false); } else if (c instanceof JDialog) { ((JDialog)c).getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); ((JDialog)c).getGlassPane().setVisible(false); } getDesktopManager().endResizingFrame(frame); } _x = 0; _y = 0; __x = 0; __y = 0; startingBounds = null; resizeDir = RESIZE_NONE; } public void mousePressed(final MouseEvent e) { if (didForwardEvent(e)) return; final Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getX(), e.getY(), null); __x = e.getX(); __y = e.getY(); _x = p.x; _y = p.y; startingBounds = frame.getBounds(); resizeDir = RESIZE_NONE; if (updatePressed(e)) { return; } if (!frame.isSelected()) { try { frame.setSelected(true); } catch(final PropertyVetoException e1) {} } if (isTitleBarDraggableArea(e)) { getDesktopManager().beginDraggingFrame(frame); fDraggingFrame = true; return; } if (e.getSource() == getNorthPane()) { getDesktopManager().beginDraggingFrame(frame); return; } if (!frame.isResizable()) { return; } if (e.getSource() == frame) { discardRelease = true; return; } } // returns true if we have handled the pressed public boolean updatePressed(final MouseEvent e) { // get the component. fWhichButtonPressed = getButtonHit(e); fMouseOverPressedButton = true; repaintButtons(); return (fWhichButtonPressed >= 0); // e.getX(), e.getY() } public int getButtonHit(final MouseEvent e) { return fAquaBorder.getWhichButtonHit(frame, e.getX(), e.getY()); } public boolean isTitleBarDraggableArea(final MouseEvent e) { if (e.getSource() != frame) return false; final Point point = e.getPoint(); final Insets insets = frame.getInsets(); if (point.y < insets.top - fAquaBorder.getTitleHeight()) return false; if (point.y > insets.top) return false; if (point.x < insets.left) return false; if (point.x > frame.getWidth() - insets.left - insets.right) return false; return true; } public void mouseDragged(final MouseEvent e) { // do not forward drags // if (didForwardEvent(e)) return; if (startingBounds == null) { // (STEVE) Yucky work around for bug ID 4106552 return; } if (fWhichButtonPressed != -1) { // track the button we started on. final int newButton = getButtonHit(e); fMouseOverPressedButton = (fWhichButtonPressed == newButton); repaintButtons(); return; } final Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getX(), e.getY(), null); final int deltaX = _x - p.x; final int deltaY = _y - p.y; int newX, newY; // Handle a MOVE if (!fDraggingFrame && e.getSource() != getNorthPane()) return; if (frame.isMaximum() || ((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK)) { // don't allow moving of frames if maximixed or left mouse // button was not used. return; } final Dimension s = frame.getParent().getSize(); final int pWidth = s.width; final int pHeight = s.height; final Insets i = frame.getInsets(); newX = startingBounds.x - deltaX; newY = startingBounds.y - deltaY; // Make sure we stay in-bounds if (newX + i.left <= -__x) newX = -__x - i.left; if (newY + i.top <= -__y) newY = -__y - i.top; if (newX + __x + i.right > pWidth) newX = pWidth - __x - i.right; if (newY + __y + i.bottom > pHeight) newY = pHeight - __y - i.bottom; getDesktopManager().dragFrame(frame, newX, newY); return; } public void mouseMoved(final MouseEvent e) { if (didForwardEvent(e)) return; updateRollover(e); } // guards against accidental infinite recursion boolean isTryingToForwardEvent = false; boolean didForwardEvent(final MouseEvent e) { if (isTryingToForwardEvent) return true; // we didn't actually...but we wound up back where we started. isTryingToForwardEvent = true; final boolean didForwardEvent = didForwardEventInternal(e); isTryingToForwardEvent = false; return didForwardEvent; } boolean didForwardEventInternal(final MouseEvent e) { if (fDraggingFrame) return false; final Point originalPoint = e.getPoint(); if (!isEventInWindowShadow(originalPoint)) return false; final Container parent = frame.getParent(); if (!(parent instanceof JDesktopPane)) return false; final JDesktopPane pane = (JDesktopPane)parent; final Point parentPoint = SwingUtilities.convertPoint(frame, originalPoint, parent); /* // debug drawing Graphics g = parent.getGraphics(); g.setColor(Color.red); g.drawLine(parentPoint.x, parentPoint.y, parentPoint.x, parentPoint.y); */ final Component hitComponent = findComponentToHitBehindMe(pane, parentPoint); if (hitComponent == null || hitComponent == frame) return false; final Point hitComponentPoint = SwingUtilities.convertPoint(pane, parentPoint, hitComponent); hitComponent.dispatchEvent(new MouseEvent(hitComponent, e.getID(), e.getWhen(), e.getModifiers(), hitComponentPoint.x, hitComponentPoint.y, e.getClickCount(), e.isPopupTrigger(), e.getButton())); return true; } Component findComponentToHitBehindMe(final JDesktopPane pane, final Point parentPoint) { final JInternalFrame[] allFrames = pane.getAllFrames(); boolean foundSelf = false; for (final JInternalFrame f : allFrames) { if (f == frame) { foundSelf = true; continue; } if (!foundSelf) continue; final Rectangle bounds = f.getBounds(); if (bounds.contains(parentPoint)) return f; } return pane; } boolean isEventInWindowShadow(final Point point) { final Rectangle bounds = frame.getBounds(); final Insets insets = frame.getInsets(); insets.top -= fAquaBorder.getTitleHeight(); if (point.x < insets.left) return true; if (point.x > bounds.width - insets.right) return true; if (point.y < insets.top) return true; if (point.y > bounds.height - insets.bottom) return true; return false; } } static void updateComponentTreeUIActivation(final Component c, final Object active) { if (c instanceof javax.swing.JComponent) { ((javax.swing.JComponent)c).putClientProperty(AquaFocusHandler.FRAME_ACTIVE_PROPERTY, active); } Component[] children = null; if (c instanceof javax.swing.JMenu) { children = ((javax.swing.JMenu)c).getMenuComponents(); } else if (c instanceof Container) { children = ((Container)c).getComponents(); } if (children != null) { for (final Component element : children) { updateComponentTreeUIActivation(element, active); } } } class PropertyListener implements PropertyChangeListener { public void propertyChange(final PropertyChangeEvent e) { final String name = e.getPropertyName(); if (FRAME_TYPE.equals(name)) { if (e.getNewValue() instanceof String) { setFrameType((String)e.getNewValue()); } } else if (IS_PALETTE_PROPERTY.equals(name)) { if (e.getNewValue() != null) { setPalette(((Boolean)e.getNewValue()).booleanValue()); } else { setPalette(false); } // TODO: CPlatformWindow? } else if ("windowModified".equals(name) || CPlatformWindow.WINDOW_DOCUMENT_MODIFIED.equals(name)) { // repaint title bar setDocumentEdited(((Boolean)e.getNewValue()).booleanValue()); frame.repaint(0, 0, frame.getWidth(), frame.getBorder().getBorderInsets(frame).top); } else if ("resizable".equals(name) || "state".equals(name) || "iconable".equals(name) || "maximizable".equals(name) || "closable".equals(name)) { if ("resizable".equals(name)) { frame.revalidate(); } frame.repaint(); } else if ("title".equals(name)) { frame.repaint(); } else if ("componentOrientation".equals(name)) { frame.revalidate(); frame.repaint(); } else if (JInternalFrame.IS_SELECTED_PROPERTY.equals(name)) { final Component source = (Component)(e.getSource()); updateComponentTreeUIActivation(source, frame.isSelected() ? Boolean.TRUE : Boolean.FALSE); } } } // end class PaletteListener static final InternalFrameShadow documentWindowShadow = new InternalFrameShadow() { Border getForegroundShadowBorder() { return new AquaUtils.SlicedShadowBorder(new Painter() { public void paint(final Graphics g, final int x, final int y, final int w, final int h) { g.setColor(new Color(0, 0, 0, 196)); g.fillRoundRect(x, y, w, h, 16, 16); g.fillRect(x, y + h - 16, w, 16); } }, new Painter() { public void paint(final Graphics g, int x, int y, int w, int h) { g.setColor(new Color(0, 0, 0, 64)); g.drawLine(x + 2, y - 8, x + w - 2, y - 8); } }, 0, 7, 1.1f, 1.0f, 24, 51, 51, 25, 25, 25, 25); } Border getBackgroundShadowBorder() { return new AquaUtils.SlicedShadowBorder(new Painter() { public void paint(final Graphics g, final int x, final int y, final int w, final int h) { g.setColor(new Color(0, 0, 0, 128)); g.fillRoundRect(x - 3, y - 8, w + 6, h, 16, 16); g.fillRect(x - 3, y + h - 20, w + 6, 19); } }, new Painter() { public void paint(final Graphics g, int x, int y, int w, int h) { g.setColor(new Color(0, 0, 0, 32)); g.drawLine(x, y - 11, x + w - 1, y - 11); } }, 0, 0, 3.0f, 1.0f, 10, 51, 51, 25, 25, 25, 25); } }; static final InternalFrameShadow paletteWindowShadow = new InternalFrameShadow() { Border getForegroundShadowBorder() { return new AquaUtils.SlicedShadowBorder(new Painter() { public void paint(final Graphics g, final int x, final int y, final int w, final int h) { g.setColor(new Color(0, 0, 0, 128)); g.fillRect(x, y + 3, w, h - 3); } }, null, 0, 3, 1.0f, 1.0f, 10, 25, 25, 12, 12, 12, 12); } Border getBackgroundShadowBorder() { return getForegroundShadowBorder(); } }; static class CompoundUIBorder extends CompoundBorder implements UIResource { public CompoundUIBorder(final Border inside, final Border outside) { super(inside, outside); } } abstract static class InternalFrameShadow extends RecyclableSingleton<Border> { abstract Border getForegroundShadowBorder(); abstract Border getBackgroundShadowBorder(); protected Border getInstance() { final Border fgShadow = getForegroundShadowBorder(); final Border bgShadow = getBackgroundShadowBorder(); return new Border() { public Insets getBorderInsets(final Component c) { return fgShadow.getBorderInsets(c); } public boolean isBorderOpaque() { return false; } public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) { if (((JInternalFrame)c).isSelected()) { fgShadow.paintBorder(c, g, x, y, w, h); } else { bgShadow.paintBorder(c, g, x, y, w, h); } } }; } } static final RecyclableSingleton<Icon> RESIZE_ICON = new RecyclableSingleton<Icon>() { protected Icon getInstance() { return new AquaIcon.CachableJRSUIIcon(11, 11) { public void initIconPainter(final AquaPainter<JRSUIState> iconState) { iconState.state.set(Widget.GROW_BOX_TEXTURED); iconState.state.set(WindowType.UTILITY); } }; } }; class ResizeBox extends JLabel implements MouseListener, MouseMotionListener, MouseWheelListener, ComponentListener, PropertyChangeListener, UIResource { final JLayeredPane layeredPane; Dimension originalSize; Point originalLocation; public ResizeBox(final JLayeredPane layeredPane) { super(RESIZE_ICON.get()); setSize(11, 11); this.layeredPane = layeredPane; addMouseListener(this); addMouseMotionListener(this); addMouseWheelListener(this); } void addListeners() { frame.addPropertyChangeListener("resizable", this); } void removeListeners() { frame.removePropertyChangeListener("resizable", this); } void repositionResizeBox() { if (frame == null) { setSize(0, 0); } else { setSize(11, 11); } setLocation(layeredPane.getWidth() - 12, layeredPane.getHeight() - 12); } void resizeInternalFrame(final Point pt) { if (originalLocation == null || frame == null) return; final Container parent = frame.getParent(); if (!(parent instanceof JDesktopPane)) return; final Point newPoint = SwingUtilities.convertPoint(this, pt, frame); int deltaX = originalLocation.x - newPoint.x; int deltaY = originalLocation.y - newPoint.y; final Dimension min = frame.getMinimumSize(); final Dimension max = frame.getMaximumSize(); final int newX = frame.getX(); final int newY = frame.getY(); int newW = frame.getWidth(); int newH = frame.getHeight(); final Rectangle parentBounds = parent.getBounds(); if (originalSize.width - deltaX < min.width) { deltaX = originalSize.width - min.width; } else if (originalSize.width - deltaX > max.width) { deltaX = -(max.width - originalSize.width); } if (newX + originalSize.width - deltaX > parentBounds.width) { deltaX = newX + originalSize.width - parentBounds.width; } if (originalSize.height - deltaY < min.height) { deltaY = originalSize.height - min.height; } else if (originalSize.height - deltaY > max.height) { deltaY = -(max.height - originalSize.height); } if (newY + originalSize.height - deltaY > parentBounds.height) { deltaY = newY + originalSize.height - parentBounds.height; } newW = originalSize.width - deltaX; newH = originalSize.height - deltaY; getDesktopManager().resizeFrame(frame, newX, newY, newW, newH); } boolean testGrowboxPoint(final int x, final int y, final int w, final int h) { return (w - x) + (h - y) < 12; } void forwardEventToFrame(final MouseEvent e) { final Point pt = new Point(); final Component c = getComponentToForwardTo(e, pt); if (c == null) return; c.dispatchEvent(new MouseEvent(c, e.getID(), e.getWhen(), e.getModifiers(), pt.x, pt.y, e.getClickCount(), e.isPopupTrigger(), e.getButton())); } Component getComponentToForwardTo(final MouseEvent e, final Point dst) { if (frame == null) return null; final Container contentPane = frame.getContentPane(); if (contentPane == null) return null; Point pt = SwingUtilities.convertPoint(this, e.getPoint(), contentPane); final Component c = SwingUtilities.getDeepestComponentAt(contentPane, pt.x, pt.y); if (c == null) return null; pt = SwingUtilities.convertPoint(contentPane, pt, c); if (dst != null) dst.setLocation(pt); return c; } public void mouseClicked(final MouseEvent e) { forwardEventToFrame(e); } public void mouseEntered(final MouseEvent e) { } public void mouseExited(final MouseEvent e) { } public void mousePressed(final MouseEvent e) { if (frame == null) return; if (frame.isResizable() && !frame.isMaximum() && testGrowboxPoint(e.getX(), e.getY(), getWidth(), getHeight())) { originalLocation = SwingUtilities.convertPoint(this, e.getPoint(), frame); originalSize = frame.getSize(); getDesktopManager().beginResizingFrame(frame, SwingConstants.SOUTH_EAST); return; } forwardEventToFrame(e); } public void mouseReleased(final MouseEvent e) { if (originalLocation != null) { resizeInternalFrame(e.getPoint()); originalLocation = null; getDesktopManager().endResizingFrame(frame); return; } forwardEventToFrame(e); } public void mouseDragged(final MouseEvent e) { resizeInternalFrame(e.getPoint()); repositionResizeBox(); } public void mouseMoved(final MouseEvent e) { } public void mouseWheelMoved(final MouseWheelEvent e) { final Point pt = new Point(); final Component c = getComponentToForwardTo(e, pt); if (c == null) return; c.dispatchEvent(new MouseWheelEvent(c, e.getID(), e.getWhen(), e.getModifiers(), pt.x, pt.y, e.getClickCount(), e.isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e.getWheelRotation())); } public void componentResized(final ComponentEvent e) { repositionResizeBox(); } public void componentShown(final ComponentEvent e) { repositionResizeBox(); } public void componentMoved(final ComponentEvent e) { repositionResizeBox(); } public void componentHidden(final ComponentEvent e) { } public void propertyChange(final PropertyChangeEvent evt) { if (!"resizable".equals(evt.getPropertyName())) return; setVisible(Boolean.TRUE.equals(evt.getNewValue())); } } }
apache/flink
36,561
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.io.network.partition.consumer; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.core.memory.MemorySegment; import org.apache.flink.core.memory.MemorySegmentFactory; import org.apache.flink.metrics.Counter; import org.apache.flink.runtime.checkpoint.CheckpointException; import org.apache.flink.runtime.checkpoint.CheckpointFailureReason; import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter; import org.apache.flink.runtime.event.AbstractEvent; import org.apache.flink.runtime.event.TaskEvent; import org.apache.flink.runtime.execution.CancelTaskException; import org.apache.flink.runtime.io.network.ConnectionID; import org.apache.flink.runtime.io.network.ConnectionManager; import org.apache.flink.runtime.io.network.PartitionRequestClient; import org.apache.flink.runtime.io.network.api.CheckpointBarrier; import org.apache.flink.runtime.io.network.api.EventAnnouncement; import org.apache.flink.runtime.io.network.api.RecoveryMetadata; import org.apache.flink.runtime.io.network.api.serialization.EventSerializer; import org.apache.flink.runtime.io.network.buffer.Buffer; import org.apache.flink.runtime.io.network.buffer.Buffer.DataType; import org.apache.flink.runtime.io.network.buffer.BufferProvider; import org.apache.flink.runtime.io.network.buffer.FreeingBufferRecycler; import org.apache.flink.runtime.io.network.buffer.NetworkBuffer; import org.apache.flink.runtime.io.network.logger.NetworkActionsLogger; import org.apache.flink.runtime.io.network.partition.PartitionNotFoundException; import org.apache.flink.runtime.io.network.partition.PrioritizedDeque; import org.apache.flink.runtime.io.network.partition.ResultPartitionID; import org.apache.flink.runtime.io.network.partition.ResultSubpartitionIndexSet; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.shaded.guava33.com.google.common.collect.Iterators; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.OptionalLong; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static org.apache.flink.runtime.io.network.buffer.Buffer.DataType.RECOVERY_METADATA; import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.flink.util.Preconditions.checkNotNull; import static org.apache.flink.util.Preconditions.checkState; /** An input channel, which requests a remote partition queue. */ public class RemoteInputChannel extends InputChannel { private static final Logger LOG = LoggerFactory.getLogger(RemoteInputChannel.class); private static final int NONE = -1; /** ID to distinguish this channel from other channels sharing the same TCP connection. */ private final InputChannelID id = new InputChannelID(); /** The connection to use to request the remote partition. */ private final ConnectionID connectionId; /** The connection manager to use connect to the remote partition provider. */ private final ConnectionManager connectionManager; /** * The received buffers. Received buffers are enqueued by the network I/O thread and the queue * is consumed by the receiving task thread. */ private final PrioritizedDeque<SequenceBuffer> receivedBuffers = new PrioritizedDeque<>(); /** * Flag indicating whether this channel has been released. Either called by the receiving task * thread or the task manager actor. */ private final AtomicBoolean isReleased = new AtomicBoolean(); /** Client to establish a (possibly shared) TCP connection and request the partition. */ private volatile PartitionRequestClient partitionRequestClient; /** The next expected sequence number for the next buffer. */ private int expectedSequenceNumber = 0; /** The initial number of exclusive buffers assigned to this channel. */ private final int initialCredit; /** The milliseconds timeout for partition request listener in result partition manager. */ private final int partitionRequestListenerTimeout; /** The number of available buffers that have not been announced to the producer yet. */ private final AtomicInteger unannouncedCredit = new AtomicInteger(0); private final BufferManager bufferManager; @GuardedBy("receivedBuffers") private int lastBarrierSequenceNumber = NONE; @GuardedBy("receivedBuffers") private long lastBarrierId = NONE; private final ChannelStatePersister channelStatePersister; private long totalQueueSizeInBytes; public RemoteInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartitionID partitionId, ResultSubpartitionIndexSet consumedSubpartitionIndexSet, ConnectionID connectionId, ConnectionManager connectionManager, int initialBackOff, int maxBackoff, int partitionRequestListenerTimeout, int networkBuffersPerChannel, Counter numBytesIn, Counter numBuffersIn, ChannelStateWriter stateWriter) { super( inputGate, channelIndex, partitionId, consumedSubpartitionIndexSet, initialBackOff, maxBackoff, numBytesIn, numBuffersIn); checkArgument(networkBuffersPerChannel >= 0, "Must be non-negative."); this.partitionRequestListenerTimeout = partitionRequestListenerTimeout; this.initialCredit = networkBuffersPerChannel; this.connectionId = checkNotNull(connectionId); this.connectionManager = checkNotNull(connectionManager); this.bufferManager = new BufferManager(inputGate.getMemorySegmentProvider(), this, 0); this.channelStatePersister = new ChannelStatePersister(stateWriter, getChannelInfo()); } @VisibleForTesting void setExpectedSequenceNumber(int expectedSequenceNumber) { this.expectedSequenceNumber = expectedSequenceNumber; } /** * Setup includes assigning exclusive buffers to this input channel, and this method should be * called only once after this input channel is created. */ @Override void setup() throws IOException { checkState( bufferManager.unsynchronizedGetAvailableExclusiveBuffers() == 0, "Bug in input channel setup logic: exclusive buffers have already been set for this input channel."); bufferManager.requestExclusiveBuffers(initialCredit); } // ------------------------------------------------------------------------ // Consume // ------------------------------------------------------------------------ /** Requests a remote subpartition. */ @VisibleForTesting @Override public void requestSubpartitions() throws IOException, InterruptedException { if (partitionRequestClient == null) { LOG.debug( "{}: Requesting REMOTE subpartitions {} of partition {}. {}", this, consumedSubpartitionIndexSet, partitionId, channelStatePersister); // Create a client and request the partition try { partitionRequestClient = connectionManager.createPartitionRequestClient(connectionId); } catch (IOException e) { // IOExceptions indicate that we could not open a connection to the remote // TaskExecutor throw new PartitionConnectionException(partitionId, e); } partitionRequestClient.requestSubpartition( partitionId, consumedSubpartitionIndexSet, this, 0); } } /** Retriggers a remote subpartition request. */ void retriggerSubpartitionRequest() throws IOException { checkPartitionRequestQueueInitialized(); if (increaseBackoff()) { partitionRequestClient.requestSubpartition( partitionId, consumedSubpartitionIndexSet, this, 0); } else { failPartitionRequest(); } } /** * The remote task manager creates partition request listener and returns {@link * PartitionNotFoundException} until the listener is timeout, so the backoff should add the * timeout milliseconds if it exists. * * @return <code>true</code>, iff the operation was successful. Otherwise, <code>false</code>. */ @Override protected boolean increaseBackoff() { if (partitionRequestListenerTimeout > 0) { currentBackoff += partitionRequestListenerTimeout; return currentBackoff < 2 * maxBackoff; } // Backoff is disabled return false; } @Override protected int peekNextBufferSubpartitionIdInternal() throws IOException { checkPartitionRequestQueueInitialized(); synchronized (receivedBuffers) { final SequenceBuffer next = receivedBuffers.peek(); if (next != null) { return next.subpartitionId; } else { return -1; } } } @Override public Optional<BufferAndAvailability> getNextBuffer() throws IOException { checkPartitionRequestQueueInitialized(); final SequenceBuffer next; final DataType nextDataType; synchronized (receivedBuffers) { next = receivedBuffers.poll(); if (next != null) { totalQueueSizeInBytes -= next.buffer.getSize(); } nextDataType = receivedBuffers.peek() != null ? receivedBuffers.peek().buffer.getDataType() : DataType.NONE; } if (next == null) { if (isReleased.get()) { throw new CancelTaskException( "Queried for a buffer after channel has been released."); } return Optional.empty(); } NetworkActionsLogger.traceInput( "RemoteInputChannel#getNextBuffer", next.buffer, inputGate.getOwningTaskName(), channelInfo, channelStatePersister, next.sequenceNumber); numBytesIn.inc(next.buffer.getSize()); numBuffersIn.inc(); return Optional.of( new BufferAndAvailability(next.buffer, nextDataType, 0, next.sequenceNumber)); } // ------------------------------------------------------------------------ // Task events // ------------------------------------------------------------------------ @Override void sendTaskEvent(TaskEvent event) throws IOException { checkState( !isReleased.get(), "Tried to send task event to producer after channel has been released."); checkPartitionRequestQueueInitialized(); partitionRequestClient.sendTaskEvent(partitionId, event, this); } // ------------------------------------------------------------------------ // Life cycle // ------------------------------------------------------------------------ @Override public boolean isReleased() { return isReleased.get(); } /** Releases all exclusive and floating buffers, closes the partition request client. */ @Override void releaseAllResources() throws IOException { if (isReleased.compareAndSet(false, true)) { final ArrayDeque<Buffer> releasedBuffers; synchronized (receivedBuffers) { releasedBuffers = receivedBuffers.stream() .map(sb -> sb.buffer) .collect(Collectors.toCollection(ArrayDeque::new)); receivedBuffers.clear(); } bufferManager.releaseAllBuffers(releasedBuffers); // The released flag has to be set before closing the connection to ensure that // buffers received concurrently with closing are properly recycled. if (partitionRequestClient != null) { partitionRequestClient.close(this); } else { connectionManager.closeOpenChannelConnections(connectionId); } } } @Override int getBuffersInUseCount() { return getNumberOfQueuedBuffers() + Math.max(0, bufferManager.getNumberOfRequiredBuffers() - initialCredit); } @Override void announceBufferSize(int newBufferSize) { try { notifyNewBufferSize(newBufferSize); } catch (Throwable t) { ExceptionUtils.rethrow(t); } } private void failPartitionRequest() { setError(new PartitionNotFoundException(partitionId)); } @Override public String toString() { return "RemoteInputChannel [" + partitionId + " at " + connectionId + "]"; } // ------------------------------------------------------------------------ // Credit-based // ------------------------------------------------------------------------ /** * Enqueue this input channel in the pipeline for notifying the producer of unannounced credit. */ private void notifyCreditAvailable() throws IOException { checkPartitionRequestQueueInitialized(); partitionRequestClient.notifyCreditAvailable(this); } private void notifyNewBufferSize(int newBufferSize) throws IOException { checkState(!isReleased.get(), "Channel released."); checkPartitionRequestQueueInitialized(); partitionRequestClient.notifyNewBufferSize(this, newBufferSize); } @VisibleForTesting public int getNumberOfAvailableBuffers() { return bufferManager.getNumberOfAvailableBuffers(); } @VisibleForTesting public int getNumberOfRequiredBuffers() { return bufferManager.unsynchronizedGetNumberOfRequiredBuffers(); } @VisibleForTesting public int getSenderBacklog() { return getNumberOfRequiredBuffers() - initialCredit; } @VisibleForTesting boolean isWaitingForFloatingBuffers() { return bufferManager.unsynchronizedIsWaitingForFloatingBuffers(); } @VisibleForTesting public Buffer getNextReceivedBuffer() { final SequenceBuffer sequenceBuffer = receivedBuffers.poll(); return sequenceBuffer != null ? sequenceBuffer.buffer : null; } @VisibleForTesting BufferManager getBufferManager() { return bufferManager; } @VisibleForTesting PartitionRequestClient getPartitionRequestClient() { return partitionRequestClient; } /** * The unannounced credit is increased by the given amount and might notify increased credit to * the producer. */ @Override public void notifyBufferAvailable(int numAvailableBuffers) throws IOException { if (numAvailableBuffers > 0 && unannouncedCredit.getAndAdd(numAvailableBuffers) == 0) { notifyCreditAvailable(); } } @Override public void resumeConsumption() throws IOException { checkState(!isReleased.get(), "Channel released."); checkPartitionRequestQueueInitialized(); if (initialCredit == 0) { // this unannounced credit can be a positive value because credit assignment and the // increase of this value is not an atomic operation and as a result, this unannounced // credit value can be get increased even after this channel has been blocked and all // floating credits are released, it is important to clear this unannounced credit and // at the same time reset the sender's available credits to keep consistency unannouncedCredit.set(0); } // notifies the producer that this channel is ready to // unblock from checkpoint and resume data consumption partitionRequestClient.resumeConsumption(this); } @Override public void acknowledgeAllRecordsProcessed() throws IOException { checkState(!isReleased.get(), "Channel released."); checkPartitionRequestQueueInitialized(); partitionRequestClient.acknowledgeAllRecordsProcessed(this); } private void onBlockingUpstream() { if (initialCredit == 0) { // release the allocated floating buffers so that they can be used by other channels if // no exclusive buffer is configured, it is important because a blocked channel can not // transmit any data so the allocated floating buffers can not be recycled, as a result, // other channels may can't allocate new buffers for data transmission (an extreme case // is that we only have 1 floating buffer and 0 exclusive buffer) bufferManager.releaseFloatingBuffers(); } } // ------------------------------------------------------------------------ // Network I/O notifications (called by network I/O thread) // ------------------------------------------------------------------------ /** * Gets the currently unannounced credit. * * @return Credit which was not announced to the sender yet. */ public int getUnannouncedCredit() { return unannouncedCredit.get(); } /** * Gets the unannounced credit and resets it to <tt>0</tt> atomically. * * @return Credit which was not announced to the sender yet. */ public int getAndResetUnannouncedCredit() { return unannouncedCredit.getAndSet(0); } /** * Gets the current number of received buffers which have not been processed yet. * * @return Buffers queued for processing. */ public int getNumberOfQueuedBuffers() { synchronized (receivedBuffers) { return receivedBuffers.size(); } } @Override public int unsynchronizedGetNumberOfQueuedBuffers() { return Math.max(0, receivedBuffers.size()); } @Override public long unsynchronizedGetSizeOfQueuedBuffers() { return Math.max(0, totalQueueSizeInBytes); } public int unsynchronizedGetExclusiveBuffersUsed() { return Math.max( 0, initialCredit - bufferManager.unsynchronizedGetAvailableExclusiveBuffers()); } public int unsynchronizedGetFloatingBuffersAvailable() { return Math.max(0, bufferManager.unsynchronizedGetFloatingBuffersAvailable()); } public InputChannelID getInputChannelId() { return id; } public int getInitialCredit() { return initialCredit; } public BufferProvider getBufferProvider() throws IOException { if (isReleased.get()) { return null; } return inputGate.getBufferProvider(); } /** * Requests buffer from input channel directly for receiving network data. It should always * return an available buffer in credit-based mode unless the channel has been released. * * @return The available buffer. */ @Nullable public Buffer requestBuffer() { return bufferManager.requestBuffer(); } /** * Receives the backlog from the producer's buffer response. If the number of available buffers * is less than backlog + initialCredit, it will request floating buffers from the buffer * manager, and then notify unannounced credits to the producer. * * @param backlog The number of unsent buffers in the producer's sub partition. */ public void onSenderBacklog(int backlog) throws IOException { notifyBufferAvailable(bufferManager.requestFloatingBuffers(backlog + initialCredit)); } /** * Handles the input buffer. This method is taking over the ownership of the buffer and is fully * responsible for cleaning it up both on the happy path and in case of an error. */ public void onBuffer(Buffer buffer, int sequenceNumber, int backlog, int subpartitionId) throws IOException { boolean recycleBuffer = true; try { if (expectedSequenceNumber != sequenceNumber) { onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber)); return; } if (buffer.getDataType().isBlockingUpstream()) { onBlockingUpstream(); checkArgument(backlog == 0, "Illegal number of backlog: %s, should be 0.", backlog); } final boolean wasEmpty; boolean firstPriorityEvent = false; synchronized (receivedBuffers) { NetworkActionsLogger.traceInput( "RemoteInputChannel#onBuffer", buffer, inputGate.getOwningTaskName(), channelInfo, channelStatePersister, sequenceNumber); // Similar to notifyBufferAvailable(), make sure that we never add a buffer // after releaseAllResources() released all buffers from receivedBuffers // (see above for details). if (isReleased.get()) { return; } wasEmpty = receivedBuffers.isEmpty(); SequenceBuffer sequenceBuffer = new SequenceBuffer(buffer, sequenceNumber, subpartitionId); DataType dataType = buffer.getDataType(); if (dataType.hasPriority()) { firstPriorityEvent = addPriorityBuffer(sequenceBuffer); recycleBuffer = false; } else { receivedBuffers.add(sequenceBuffer); recycleBuffer = false; if (dataType.requiresAnnouncement()) { firstPriorityEvent = addPriorityBuffer(announce(sequenceBuffer)); } } totalQueueSizeInBytes += buffer.getSize(); final OptionalLong barrierId = channelStatePersister.checkForBarrier(sequenceBuffer.buffer); if (barrierId.isPresent() && barrierId.getAsLong() > lastBarrierId) { // checkpoint was not yet started by task thread, // so remember the numbers of buffers to spill for the time when // it will be started lastBarrierId = barrierId.getAsLong(); lastBarrierSequenceNumber = sequenceBuffer.sequenceNumber; } channelStatePersister.maybePersist(buffer); ++expectedSequenceNumber; } if (firstPriorityEvent) { notifyPriorityEvent(sequenceNumber); } if (wasEmpty) { notifyChannelNonEmpty(); } if (backlog >= 0) { onSenderBacklog(backlog); } } finally { if (recycleBuffer) { buffer.recycleBuffer(); } } } /** * @return {@code true} if this was first priority buffer added. */ private boolean addPriorityBuffer(SequenceBuffer sequenceBuffer) { receivedBuffers.addPriorityElement(sequenceBuffer); return receivedBuffers.getNumPriorityElements() == 1; } private SequenceBuffer announce(SequenceBuffer sequenceBuffer) throws IOException { checkState( !sequenceBuffer.buffer.isBuffer(), "Only a CheckpointBarrier can be announced but found %s", sequenceBuffer.buffer); checkAnnouncedOnlyOnce(sequenceBuffer); AbstractEvent event = EventSerializer.fromBuffer(sequenceBuffer.buffer, getClass().getClassLoader()); checkState( event instanceof CheckpointBarrier, "Only a CheckpointBarrier can be announced but found %s", sequenceBuffer.buffer); CheckpointBarrier barrier = (CheckpointBarrier) event; return new SequenceBuffer( EventSerializer.toBuffer( new EventAnnouncement(barrier, sequenceBuffer.sequenceNumber), true), sequenceBuffer.sequenceNumber, sequenceBuffer.subpartitionId); } private void checkAnnouncedOnlyOnce(SequenceBuffer sequenceBuffer) { Iterator<SequenceBuffer> iterator = receivedBuffers.iterator(); int count = 0; while (iterator.hasNext()) { if (iterator.next().sequenceNumber == sequenceBuffer.sequenceNumber) { count++; } } checkState( count == 1, "Before enqueuing the announcement there should be exactly single occurrence of the buffer, but found [%d]", count); } /** * Spills all queued buffers on checkpoint start. If barrier has already been received (and * reordered), spill only the overtaken buffers. */ public void checkpointStarted(CheckpointBarrier barrier) throws CheckpointException { synchronized (receivedBuffers) { if (barrier.getId() < lastBarrierId) { throw new CheckpointException( String.format( "Sequence number for checkpoint %d is not known (it was likely been overwritten by a newer checkpoint %d)", barrier.getId(), lastBarrierId), CheckpointFailureReason .CHECKPOINT_SUBSUMED); // currently, at most one active unaligned // checkpoint is possible } else if (barrier.getId() > lastBarrierId) { // This channel has received some obsolete barrier, older compared to the // checkpointId // which we are processing right now, and we should ignore that obsoleted checkpoint // barrier sequence number. resetLastBarrier(); } channelStatePersister.startPersisting( barrier.getId(), getInflightBuffersUnsafe(barrier.getId())); } } public void checkpointStopped(long checkpointId) { synchronized (receivedBuffers) { channelStatePersister.stopPersisting(checkpointId); if (lastBarrierId == checkpointId) { resetLastBarrier(); } } } @VisibleForTesting List<Buffer> getInflightBuffers(long checkpointId) { synchronized (receivedBuffers) { return getInflightBuffersUnsafe(checkpointId); } } @Override public void convertToPriorityEvent(int sequenceNumber) throws IOException { boolean firstPriorityEvent; synchronized (receivedBuffers) { checkState(channelStatePersister.hasBarrierReceived()); int numPriorityElementsBeforeRemoval = receivedBuffers.getNumPriorityElements(); SequenceBuffer toPrioritize = receivedBuffers.getAndRemove( sequenceBuffer -> sequenceBuffer.sequenceNumber == sequenceNumber); checkState(lastBarrierSequenceNumber == sequenceNumber); checkState(!toPrioritize.buffer.isBuffer()); checkState( numPriorityElementsBeforeRemoval == receivedBuffers.getNumPriorityElements(), "Attempted to convertToPriorityEvent an event [%s] that has already been prioritized [%s]", toPrioritize, numPriorityElementsBeforeRemoval); // set the priority flag (checked on poll) // don't convert the barrier itself (barrier controller might not have been switched // yet) AbstractEvent e = EventSerializer.fromBuffer( toPrioritize.buffer, this.getClass().getClassLoader()); toPrioritize.buffer.setReaderIndex(0); toPrioritize = new SequenceBuffer( EventSerializer.toBuffer(e, true), toPrioritize.sequenceNumber, toPrioritize.subpartitionId); firstPriorityEvent = addPriorityBuffer( toPrioritize); // note that only position of the element is changed // converting the event itself would require switching the controller sooner } if (firstPriorityEvent) { notifyPriorityEventForce(); // forcibly notify about the priority event // instead of passing barrier SQN to be checked // because this SQN might have be seen by the input gate during the announcement } } private void notifyPriorityEventForce() { inputGate.notifyPriorityEventForce(this); } /** * Returns a list of buffers, checking the first n non-priority buffers, and skipping all * events. */ private List<Buffer> getInflightBuffersUnsafe(long checkpointId) { assert Thread.holdsLock(receivedBuffers); checkState(checkpointId == lastBarrierId || lastBarrierId == NONE); final List<Buffer> inflightBuffers = new ArrayList<>(); Iterator<SequenceBuffer> iterator = receivedBuffers.iterator(); // skip all priority events (only buffers are stored anyways) Iterators.advance(iterator, receivedBuffers.getNumPriorityElements()); int finalBufferSubpartitionId = -1; while (iterator.hasNext()) { SequenceBuffer sequenceBuffer = iterator.next(); if (sequenceBuffer.buffer.isBuffer()) { if (shouldBeSpilled(sequenceBuffer.sequenceNumber)) { inflightBuffers.add(sequenceBuffer.buffer.retainBuffer()); finalBufferSubpartitionId = sequenceBuffer.subpartitionId; } else { break; } } } if (finalBufferSubpartitionId >= 0 && consumedSubpartitionIndexSet.size() > 1) { MemorySegment memorySegment; try { memorySegment = MemorySegmentFactory.wrap( EventSerializer.toSerializedEvent( new RecoveryMetadata(finalBufferSubpartitionId)) .array()); } catch (IOException e) { throw new RuntimeException(e); } inflightBuffers.add( new NetworkBuffer( memorySegment, FreeingBufferRecycler.INSTANCE, RECOVERY_METADATA, memorySegment.size())); } return inflightBuffers; } private void resetLastBarrier() { lastBarrierId = NONE; lastBarrierSequenceNumber = NONE; } /** * @return if given {@param sequenceNumber} should be spilled given {@link * #lastBarrierSequenceNumber}. We might not have yet received {@link CheckpointBarrier} and * we might need to spill everything. If we have already received it, there is a bit nasty * corner case of {@link SequenceBuffer#sequenceNumber} overflowing that needs to be handled * as well. */ private boolean shouldBeSpilled(int sequenceNumber) { if (lastBarrierSequenceNumber == NONE) { return true; } checkState( receivedBuffers.size() < Integer.MAX_VALUE / 2, "Too many buffers for sequenceNumber overflow detection code to work correctly"); boolean possibleOverflowAfterOvertaking = Integer.MAX_VALUE / 2 < lastBarrierSequenceNumber; boolean possibleOverflowBeforeOvertaking = lastBarrierSequenceNumber < -Integer.MAX_VALUE / 2; if (possibleOverflowAfterOvertaking) { return sequenceNumber < lastBarrierSequenceNumber && sequenceNumber > 0; } else if (possibleOverflowBeforeOvertaking) { return sequenceNumber < lastBarrierSequenceNumber || sequenceNumber > 0; } else { return sequenceNumber < lastBarrierSequenceNumber; } } public void onEmptyBuffer(int sequenceNumber, int backlog) throws IOException { boolean success = false; synchronized (receivedBuffers) { if (!isReleased.get()) { if (expectedSequenceNumber == sequenceNumber) { expectedSequenceNumber++; success = true; } else { onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber)); } } } if (success && backlog >= 0) { onSenderBacklog(backlog); } } public void onFailedPartitionRequest() { inputGate.triggerPartitionStateCheck(partitionId, channelInfo); } public void onError(Throwable cause) { setError(cause); } private void checkPartitionRequestQueueInitialized() throws IOException { checkError(); checkState( partitionRequestClient != null, "Bug: partitionRequestClient is not initialized before processing data and no error is detected."); } @Override public void notifyRequiredSegmentId(int subpartitionId, int segmentId) throws IOException { checkState(!isReleased.get(), "Channel released."); checkPartitionRequestQueueInitialized(); partitionRequestClient.notifyRequiredSegmentId(this, subpartitionId, segmentId); } private static class BufferReorderingException extends IOException { private static final long serialVersionUID = -888282210356266816L; private final int expectedSequenceNumber; private final int actualSequenceNumber; BufferReorderingException(int expectedSequenceNumber, int actualSequenceNumber) { this.expectedSequenceNumber = expectedSequenceNumber; this.actualSequenceNumber = actualSequenceNumber; } @Override public String getMessage() { return String.format( "Buffer re-ordering: expected buffer with sequence number %d, but received %d.", expectedSequenceNumber, actualSequenceNumber); } } private static final class SequenceBuffer { final Buffer buffer; final int sequenceNumber; final int subpartitionId; private SequenceBuffer(Buffer buffer, int sequenceNumber, int subpartitionId) { this.buffer = buffer; this.sequenceNumber = sequenceNumber; this.subpartitionId = subpartitionId; } @Override public String toString() { return String.format( "SequenceBuffer(isEvent = %s, dataType = %s, sequenceNumber = %s)", !buffer.isBuffer(), buffer.getDataType(), sequenceNumber); } } }
apache/hadoop
36,027
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/test/java/org/apache/hadoop/mapreduce/v2/hs/webapp/TestHsWebServicesJobs.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapreduce.v2.hs.webapp; import static org.apache.hadoop.yarn.util.StringHelper.join; import static org.apache.hadoop.yarn.util.StringHelper.ujoin; import static org.apache.hadoop.yarn.webapp.WebServicesTestUtils.assertResponseStatusCode; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.StringReader; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.NotFoundException; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.http.JettyUtils; import org.apache.hadoop.mapreduce.v2.api.records.AMInfo; import org.apache.hadoop.mapreduce.v2.api.records.JobId; import org.apache.hadoop.mapreduce.v2.app.AppContext; import org.apache.hadoop.mapreduce.v2.app.job.Job; import org.apache.hadoop.mapreduce.v2.hs.HistoryContext; import org.apache.hadoop.mapreduce.v2.hs.MockHistoryContext; import org.apache.hadoop.mapreduce.v2.util.MRApps; import org.apache.hadoop.util.XMLUtils; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.webapp.GenericExceptionHandler; import org.apache.hadoop.yarn.webapp.JerseyTestBase; import org.apache.hadoop.yarn.webapp.WebApp; import org.apache.hadoop.yarn.webapp.WebServicesTestUtils; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.glassfish.jersey.internal.inject.AbstractBinder; import org.glassfish.jersey.jettison.JettisonFeature; import org.glassfish.jersey.server.ResourceConfig; /** * Test the history server Rest API for getting jobs, a specific job, job * counters, and job attempts. * * /ws/v1/history/mapreduce/jobs /ws/v1/history/mapreduce/jobs/{jobid} * /ws/v1/history/mapreduce/jobs/{jobid}/counters * /ws/v1/history/mapreduce/jobs/{jobid}/jobattempts */ public class TestHsWebServicesJobs extends JerseyTestBase { private static Configuration conf = new Configuration(); private static MockHistoryContext appContext; private static HsWebApp webApp; private static ApplicationClientProtocol acp = mock(ApplicationClientProtocol.class); @Override protected Application configure() { ResourceConfig config = new ResourceConfig(); config.register(new JerseyBinder()); config.register(HsWebServices.class); config.register(GenericExceptionHandler.class); config.register(new JettisonFeature()).register(JAXBContextResolver.class); return config; } private class JerseyBinder extends AbstractBinder { @Override protected void configure() { appContext = new MockHistoryContext(0, 1, 2, 1); webApp = mock(HsWebApp.class); when(webApp.name()).thenReturn("hsmockwebapp"); bind(webApp).to(WebApp.class).named("hsWebApp"); bind(appContext).to(AppContext.class); bind(appContext).to(HistoryContext.class).named("ctx"); bind(conf).to(Configuration.class).named("conf"); bind(acp).to(ApplicationClientProtocol.class).named("appClient"); final HttpServletResponse response = mock(HttpServletResponse.class); bind(response).to(HttpServletResponse.class); final HttpServletRequest request = mock(HttpServletRequest.class); bind(request).to(HttpServletRequest.class); } } @Test public void testJobs() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").request(MediaType.APPLICATION_JSON) .get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject jobs = json.getJSONObject("jobs"); JSONObject jobItem = jobs.getJSONObject("job"); JSONArray arr = new JSONArray(); arr.put(jobItem); assertEquals(1, arr.length(), "incorrect number of elements"); JSONObject info = arr.getJSONObject(0); Job job = appContext.getPartialJob(MRApps.toJobID(info.getString("id"))); VerifyJobsUtils.verifyHsJobPartial(info, job); } @Test public void testJobsSlash() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs/").request(MediaType.APPLICATION_JSON) .get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject jobs = json.getJSONObject("jobs"); JSONObject jobItem = jobs.getJSONObject("job"); JSONArray arr = new JSONArray(); arr.put(jobItem); assertEquals(1, arr.length(), "incorrect number of elements"); JSONObject info = arr.getJSONObject(0); Job job = appContext.getPartialJob(MRApps.toJobID(info.getString("id"))); VerifyJobsUtils.verifyHsJobPartial(info, job); } @Test public void testJobsDefault() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").request().get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject jobs = json.getJSONObject("jobs"); JSONObject jobItem = jobs.getJSONObject("job"); JSONArray arr = new JSONArray(); arr.put(jobItem); assertEquals(1, arr.length(), "incorrect number of elements"); JSONObject info = arr.getJSONObject(0); Job job = appContext.getPartialJob(MRApps.toJobID(info.getString("id"))); VerifyJobsUtils.verifyHsJobPartial(info, job); } @Test public void testJobsXML() throws Exception { WebTarget r = target(); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").request(MediaType.APPLICATION_XML) .get(Response.class); assertEquals(MediaType.APPLICATION_XML_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); String xml = response.readEntity(String.class); DocumentBuilderFactory dbf = XMLUtils.newSecureDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Document dom = db.parse(is); NodeList jobs = dom.getElementsByTagName("jobs"); assertEquals(1, jobs.getLength(), "incorrect number of elements"); NodeList job = dom.getElementsByTagName("job"); assertEquals(1, job.getLength(), "incorrect number of elements"); verifyHsJobPartialXML(job, appContext); } public void verifyHsJobPartialXML(NodeList nodes, MockHistoryContext appContext) { assertEquals(1, nodes.getLength(), "incorrect number of elements"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); Job job = appContext.getPartialJob(MRApps.toJobID(WebServicesTestUtils .getXmlString(element, "id"))); assertNotNull(job, "Job not found - output incorrect"); VerifyJobsUtils.verifyHsJobGeneric(job, WebServicesTestUtils.getXmlString(element, "id"), WebServicesTestUtils.getXmlString(element, "user"), WebServicesTestUtils.getXmlString(element, "name"), WebServicesTestUtils.getXmlString(element, "state"), WebServicesTestUtils.getXmlString(element, "queue"), WebServicesTestUtils.getXmlLong(element, "startTime"), WebServicesTestUtils.getXmlLong(element, "finishTime"), WebServicesTestUtils.getXmlInt(element, "mapsTotal"), WebServicesTestUtils.getXmlInt(element, "mapsCompleted"), WebServicesTestUtils.getXmlInt(element, "reducesTotal"), WebServicesTestUtils.getXmlInt(element, "reducesCompleted")); } } public void verifyHsJobXML(NodeList nodes, AppContext appContext) { assertEquals(1, nodes.getLength(), "incorrect number of elements"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); Job job = appContext.getJob(MRApps.toJobID(WebServicesTestUtils .getXmlString(element, "id"))); assertNotNull(job, "Job not found - output incorrect"); VerifyJobsUtils.verifyHsJobGeneric(job, WebServicesTestUtils.getXmlString(element, "id"), WebServicesTestUtils.getXmlString(element, "user"), WebServicesTestUtils.getXmlString(element, "name"), WebServicesTestUtils.getXmlString(element, "state"), WebServicesTestUtils.getXmlString(element, "queue"), WebServicesTestUtils.getXmlLong(element, "startTime"), WebServicesTestUtils.getXmlLong(element, "finishTime"), WebServicesTestUtils.getXmlInt(element, "mapsTotal"), WebServicesTestUtils.getXmlInt(element, "mapsCompleted"), WebServicesTestUtils.getXmlInt(element, "reducesTotal"), WebServicesTestUtils.getXmlInt(element, "reducesCompleted")); // restricted access fields - if security and acls set VerifyJobsUtils.verifyHsJobGenericSecure(job, WebServicesTestUtils.getXmlBoolean(element, "uberized"), WebServicesTestUtils.getXmlString(element, "diagnostics"), WebServicesTestUtils.getXmlLong(element, "avgMapTime"), WebServicesTestUtils.getXmlLong(element, "avgReduceTime"), WebServicesTestUtils.getXmlLong(element, "avgShuffleTime"), WebServicesTestUtils.getXmlLong(element, "avgMergeTime"), WebServicesTestUtils.getXmlInt(element, "failedReduceAttempts"), WebServicesTestUtils.getXmlInt(element, "killedReduceAttempts"), WebServicesTestUtils.getXmlInt(element, "successfulReduceAttempts"), WebServicesTestUtils.getXmlInt(element, "failedMapAttempts"), WebServicesTestUtils.getXmlInt(element, "killedMapAttempts"), WebServicesTestUtils.getXmlInt(element, "successfulMapAttempts")); } } @Test public void testJobId() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId) .request(MediaType.APPLICATION_JSON).get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("job"); VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id)); } } @Test public void testJobIdSlash() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId + "/") .request(MediaType.APPLICATION_JSON).get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("job"); VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id)); } } @Test public void testJobIdDefault() throws Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).request().get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("job"); VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id)); } } @Test public void testJobIdNonExist() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); try { Response response = r.path("ws").path("v1").path("history").path("mapreduce").path("jobs") .path("job_0_1234").request().get(); throw new NotFoundException(response); } catch (NotFoundException ue) { Response response = ue.getResponse(); assertResponseStatusCode(Response.Status.NOT_FOUND, response.getStatusInfo()); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject msg = response.readEntity(JSONObject.class); JSONObject exception = msg.getJSONObject("RemoteException"); assertEquals(3, exception.length(), "incorrect number of elements"); String message = exception.getString("message"); String type = exception.getString("exception"); String classname = exception.getString("javaClassName"); WebServicesTestUtils.checkStringMatch("exception message", "job, job_0_1234, is not found", message); WebServicesTestUtils.checkStringMatch("exception type", "NotFoundException", type); WebServicesTestUtils.checkStringMatch("exception classname", "org.apache.hadoop.yarn.webapp.NotFoundException", classname); } } @Test public void testJobIdInvalid() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); try { Response response = r.path("ws").path("v1").path("history").path("mapreduce").path("jobs") .path("job_foo").request(MediaType.APPLICATION_JSON).get(); throw new NotFoundException(response); } catch (NotFoundException ue) { Response response = ue.getResponse(); assertResponseStatusCode(Response.Status.NOT_FOUND, response.getStatusInfo()); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject msg = response.readEntity(JSONObject.class); JSONObject exception = msg.getJSONObject("RemoteException"); assertEquals(3, exception.length(), "incorrect number of elements"); String message = exception.getString("message"); String type = exception.getString("exception"); String classname = exception.getString("javaClassName"); verifyJobIdInvalid(message, type, classname); } } // verify the exception output default is JSON @Test public void testJobIdInvalidDefault() throws JSONException, Exception { WebTarget r = target(); try { Response response = r.path("ws").path("v1").path("history").path("mapreduce").path("jobs") .path("job_foo").request().get(); throw new NotFoundException(response); } catch (NotFoundException ue) { Response response = ue.getResponse(); assertResponseStatusCode(Response.Status.NOT_FOUND, response.getStatusInfo()); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); String entity = response.readEntity(String.class); JSONObject msg = new JSONObject(entity); JSONObject exception = msg.getJSONObject("RemoteException"); assertEquals(3, exception.length(), "incorrect number of elements"); String message = exception.getString("message"); String type = exception.getString("exception"); String classname = exception.getString("javaClassName"); verifyJobIdInvalid(message, type, classname); } } // test that the exception output works in XML @Test public void testJobIdInvalidXML() throws JSONException, Exception { WebTarget r = target(); try { Response response = r.path("ws").path("v1").path("history").path("mapreduce").path("jobs") .path("job_foo").request(MediaType.APPLICATION_XML) .get(); throw new NotFoundException(response); } catch (NotFoundException ue) { Response response = ue.getResponse(); assertResponseStatusCode(Response.Status.NOT_FOUND, response.getStatusInfo()); assertEquals(MediaType.APPLICATION_XML_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); String msg = response.readEntity(String.class); DocumentBuilderFactory dbf = XMLUtils.newSecureDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(msg)); Document dom = db.parse(is); NodeList nodes = dom.getElementsByTagName("RemoteException"); Element element = (Element) nodes.item(0); String message = WebServicesTestUtils.getXmlString(element, "message"); String type = WebServicesTestUtils.getXmlString(element, "exception"); String classname = WebServicesTestUtils.getXmlString(element, "javaClassName"); verifyJobIdInvalid(message, type, classname); } } private void verifyJobIdInvalid(String message, String type, String classname) { WebServicesTestUtils.checkStringMatch("exception message", "JobId string : job_foo is not properly formed", message); WebServicesTestUtils.checkStringMatch("exception type", "NotFoundException", type); WebServicesTestUtils.checkStringMatch("exception classname", "org.apache.hadoop.yarn.webapp.NotFoundException", classname); } @Test public void testJobIdInvalidBogus() throws JSONException, Exception { WebTarget r = target(); try { Response response = r.path("ws").path("v1").path("history").path("mapreduce").path("jobs") .path("bogusfoo").request(MediaType.APPLICATION_JSON) .get(); throw new NotFoundException(response); } catch (NotFoundException ue) { Response response = ue.getResponse(); assertResponseStatusCode(Response.Status.NOT_FOUND, response.getStatusInfo()); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); String entity = response.readEntity(String.class); JSONObject msg = new JSONObject(entity); JSONObject exception = msg.getJSONObject("RemoteException"); assertEquals(3, exception.length(), "incorrect number of elements"); String message = exception.getString("message"); String type = exception.getString("exception"); String classname = exception.getString("javaClassName"); WebServicesTestUtils.checkStringMatch("exception message", "JobId string : bogusfoo is not properly formed", message); WebServicesTestUtils.checkStringMatch("exception type", "NotFoundException", type); WebServicesTestUtils.checkStringMatch("exception classname", "org.apache.hadoop.yarn.webapp.NotFoundException", classname); } } @Test public void testJobIdXML() throws Exception { WebTarget r = target(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId) .request(MediaType.APPLICATION_XML).get(Response.class); assertEquals(MediaType.APPLICATION_XML_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); String xml = response.readEntity(String.class); DocumentBuilderFactory dbf = XMLUtils.newSecureDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Document dom = db.parse(is); NodeList job = dom.getElementsByTagName("job"); verifyHsJobXML(job, appContext); } } @Test public void testJobCounters() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("counters") .request(MediaType.APPLICATION_JSON).get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("jobCounters"); verifyHsJobCounters(info, appContext.getJob(id)); } } @Test public void testJobCountersSlash() throws Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("counters/") .request(MediaType.APPLICATION_JSON).get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("jobCounters"); verifyHsJobCounters(info, appContext.getJob(id)); } } @Test public void testJobCountersForKilledJob() throws Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("counters/") .request(MediaType.APPLICATION_JSON).get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("jobCounters"); WebServicesTestUtils.checkStringMatch("id", MRApps.toString(id), info.getString("id")); // The modification in this test case is because // we have unified all the context parameters in this unit test, // and the value of this variable has been changed to 2. assertTrue(info.length() == 2, "Job shouldn't contain any counters"); } } @Test public void testJobCountersDefault() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("counters/") .request().get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("jobCounters"); verifyHsJobCounters(info, appContext.getJob(id)); } } @Test public void testJobCountersXML() throws Exception { WebTarget r = target(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("counters") .request(MediaType.APPLICATION_XML).get(Response.class); assertEquals(MediaType.APPLICATION_XML_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); String xml = response.readEntity(String.class); DocumentBuilderFactory dbf = XMLUtils.newSecureDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Document dom = db.parse(is); NodeList info = dom.getElementsByTagName("jobCounters"); verifyHsJobCountersXML(info, appContext.getJob(id)); } } public void verifyHsJobCounters(JSONObject info, Job job) throws JSONException { assertEquals(2, info.length(), "incorrect number of elements"); WebServicesTestUtils.checkStringMatch("id", MRApps.toString(job.getID()), info.getString("id")); // just do simple verification of fields - not data is correct // in the fields JSONArray counterGroups = info.getJSONArray("counterGroup"); for (int i = 0; i < counterGroups.length(); i++) { JSONObject counterGroup = counterGroups.getJSONObject(i); String name = counterGroup.getString("counterGroupName"); assertTrue((name != null && !name.isEmpty()), "name not set"); JSONArray counters = counterGroup.getJSONArray("counter"); for (int j = 0; j < counters.length(); j++) { JSONObject counter = counters.getJSONObject(j); String counterName = counter.getString("name"); assertTrue((counterName != null && !counterName.isEmpty()), "counter name not set"); long mapValue = counter.getLong("mapCounterValue"); assertTrue(mapValue >= 0, "mapCounterValue >= 0"); long reduceValue = counter.getLong("reduceCounterValue"); assertTrue(reduceValue >= 0, "reduceCounterValue >= 0"); long totalValue = counter.getLong("totalCounterValue"); assertTrue(totalValue >= 0, "totalCounterValue >= 0"); } } } public void verifyHsJobCountersXML(NodeList nodes, Job job) { for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); assertNotNull(job, "Job not found - output incorrect"); WebServicesTestUtils.checkStringMatch("id", MRApps.toString(job.getID()), WebServicesTestUtils.getXmlString(element, "id")); // just do simple verification of fields - not data is correct // in the fields NodeList groups = element.getElementsByTagName("counterGroup"); for (int j = 0; j < groups.getLength(); j++) { Element counters = (Element) groups.item(j); assertNotNull(counters, "should have counters in the web service info"); String name = WebServicesTestUtils.getXmlString(counters, "counterGroupName"); assertTrue((name != null && !name.isEmpty()), "name not set"); NodeList counterArr = counters.getElementsByTagName("counter"); for (int z = 0; z < counterArr.getLength(); z++) { Element counter = (Element) counterArr.item(z); String counterName = WebServicesTestUtils.getXmlString(counter, "name"); assertTrue((counterName != null && !counterName.isEmpty()), "counter name not set"); long mapValue = WebServicesTestUtils.getXmlLong(counter, "mapCounterValue"); assertTrue(mapValue >= 0, "mapCounterValue not >= 0"); long reduceValue = WebServicesTestUtils.getXmlLong(counter, "reduceCounterValue"); assertTrue(reduceValue >= 0, "reduceCounterValue >= 0"); long totalValue = WebServicesTestUtils.getXmlLong(counter, "totalCounterValue"); assertTrue(totalValue >= 0, "totalCounterValue >= 0"); } } } } @Test public void testJobAttempts() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("jobattempts") .request(MediaType.APPLICATION_JSON).get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("jobAttempts"); verifyHsJobAttempts(info, appContext.getJob(id)); } } @Test public void testJobAttemptsSlash() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("jobattempts/") .request(MediaType.APPLICATION_JSON).get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("jobAttempts"); verifyHsJobAttempts(info, appContext.getJob(id)); } } @Test public void testJobAttemptsDefault() throws JSONException, Exception { WebTarget r = targetWithJsonObject(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("jobattempts") .request() .get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject info = json.getJSONObject("jobAttempts"); verifyHsJobAttempts(info, appContext.getJob(id)); } } @Test public void testJobAttemptsXML() throws Exception { WebTarget r = target(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); Response response = r.path("ws").path("v1").path("history") .path("mapreduce").path("jobs").path(jobId).path("jobattempts") .request(MediaType.APPLICATION_XML).get(Response.class); assertEquals(MediaType.APPLICATION_XML_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); String xml = response.readEntity(String.class); DocumentBuilderFactory dbf = XMLUtils.newSecureDocumentBuilderFactory(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Document dom = db.parse(is); NodeList attempts = dom.getElementsByTagName("jobAttempts"); assertEquals(1, attempts.getLength(), "incorrect number of elements"); NodeList info = dom.getElementsByTagName("jobAttempt"); verifyHsJobAttemptsXML(info, appContext.getJob(id)); } } public void verifyHsJobAttempts(JSONObject info, Job job) throws JSONException { JSONArray attempts = info.getJSONArray("jobAttempt"); assertEquals(2, attempts.length(), "incorrect number of elements"); for (int i = 0; i < attempts.length(); i++) { JSONObject attempt = attempts.getJSONObject(i); verifyHsJobAttemptsGeneric(job, attempt.getString("nodeHttpAddress"), attempt.getString("nodeId"), attempt.getInt("id"), attempt.getLong("startTime"), attempt.getString("containerId"), attempt.getString("logsLink")); } } public void verifyHsJobAttemptsXML(NodeList nodes, Job job) { assertEquals(2, nodes.getLength(), "incorrect number of elements"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); verifyHsJobAttemptsGeneric(job, WebServicesTestUtils.getXmlString(element, "nodeHttpAddress"), WebServicesTestUtils.getXmlString(element, "nodeId"), WebServicesTestUtils.getXmlInt(element, "id"), WebServicesTestUtils.getXmlLong(element, "startTime"), WebServicesTestUtils.getXmlString(element, "containerId"), WebServicesTestUtils.getXmlString(element, "logsLink")); } } public void verifyHsJobAttemptsGeneric(Job job, String nodeHttpAddress, String nodeId, int id, long startTime, String containerId, String logsLink) { boolean attemptFound = false; for (AMInfo amInfo : job.getAMInfos()) { if (amInfo.getAppAttemptId().getAttemptId() == id) { attemptFound = true; String nmHost = amInfo.getNodeManagerHost(); int nmHttpPort = amInfo.getNodeManagerHttpPort(); int nmPort = amInfo.getNodeManagerPort(); WebServicesTestUtils.checkStringMatch("nodeHttpAddress", nmHost + ":" + nmHttpPort, nodeHttpAddress); assertTrue(startTime > 0, "startime not greater than 0"); WebServicesTestUtils.checkStringMatch("containerId", amInfo .getContainerId().toString(), containerId); String localLogsLink = join("hsmockwebapp", ujoin("logs", nodeId, containerId, MRApps.toString(job.getID()), job.getUserName())); assertTrue(logsLink.contains(localLogsLink), "logsLink"); } } assertTrue(attemptFound, "attempt: " + id + " was not found"); } }
googleapis/google-cloud-java
36,353
java-datacatalog/proto-google-cloud-datacatalog-v1beta1/src/main/java/com/google/cloud/datacatalog/v1beta1/UpdateTagRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datacatalog/v1beta1/datacatalog.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datacatalog.v1beta1; /** * * * <pre> * Request message for * [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. * </pre> * * Protobuf type {@code google.cloud.datacatalog.v1beta1.UpdateTagRequest} */ public final class UpdateTagRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1beta1.UpdateTagRequest) UpdateTagRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateTagRequest.newBuilder() to construct. private UpdateTagRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateTagRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateTagRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datacatalog.v1beta1.Datacatalog .internal_static_google_cloud_datacatalog_v1beta1_UpdateTagRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datacatalog.v1beta1.Datacatalog .internal_static_google_cloud_datacatalog_v1beta1_UpdateTagRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datacatalog.v1beta1.UpdateTagRequest.class, com.google.cloud.datacatalog.v1beta1.UpdateTagRequest.Builder.class); } private int bitField0_; public static final int TAG_FIELD_NUMBER = 1; private com.google.cloud.datacatalog.v1beta1.Tag tag_; /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tag field is set. */ @java.lang.Override public boolean hasTag() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tag. */ @java.lang.Override public com.google.cloud.datacatalog.v1beta1.Tag getTag() { return tag_ == null ? com.google.cloud.datacatalog.v1beta1.Tag.getDefaultInstance() : tag_; } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.datacatalog.v1beta1.TagOrBuilder getTagOrBuilder() { return tag_ == null ? com.google.cloud.datacatalog.v1beta1.Tag.getDefaultInstance() : tag_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getTag()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateMask()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getTag()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datacatalog.v1beta1.UpdateTagRequest)) { return super.equals(obj); } com.google.cloud.datacatalog.v1beta1.UpdateTagRequest other = (com.google.cloud.datacatalog.v1beta1.UpdateTagRequest) obj; if (hasTag() != other.hasTag()) return false; if (hasTag()) { if (!getTag().equals(other.getTag())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasTag()) { hash = (37 * hash) + TAG_FIELD_NUMBER; hash = (53 * hash) + getTag().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datacatalog.v1beta1.UpdateTagRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for * [UpdateTag][google.cloud.datacatalog.v1beta1.DataCatalog.UpdateTag]. * </pre> * * Protobuf type {@code google.cloud.datacatalog.v1beta1.UpdateTagRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1beta1.UpdateTagRequest) com.google.cloud.datacatalog.v1beta1.UpdateTagRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datacatalog.v1beta1.Datacatalog .internal_static_google_cloud_datacatalog_v1beta1_UpdateTagRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datacatalog.v1beta1.Datacatalog .internal_static_google_cloud_datacatalog_v1beta1_UpdateTagRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datacatalog.v1beta1.UpdateTagRequest.class, com.google.cloud.datacatalog.v1beta1.UpdateTagRequest.Builder.class); } // Construct using com.google.cloud.datacatalog.v1beta1.UpdateTagRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTagFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; tag_ = null; if (tagBuilder_ != null) { tagBuilder_.dispose(); tagBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datacatalog.v1beta1.Datacatalog .internal_static_google_cloud_datacatalog_v1beta1_UpdateTagRequest_descriptor; } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTagRequest getDefaultInstanceForType() { return com.google.cloud.datacatalog.v1beta1.UpdateTagRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTagRequest build() { com.google.cloud.datacatalog.v1beta1.UpdateTagRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTagRequest buildPartial() { com.google.cloud.datacatalog.v1beta1.UpdateTagRequest result = new com.google.cloud.datacatalog.v1beta1.UpdateTagRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.datacatalog.v1beta1.UpdateTagRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.tag_ = tagBuilder_ == null ? tag_ : tagBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datacatalog.v1beta1.UpdateTagRequest) { return mergeFrom((com.google.cloud.datacatalog.v1beta1.UpdateTagRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datacatalog.v1beta1.UpdateTagRequest other) { if (other == com.google.cloud.datacatalog.v1beta1.UpdateTagRequest.getDefaultInstance()) return this; if (other.hasTag()) { mergeTag(other.getTag()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getTagFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.datacatalog.v1beta1.Tag tag_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datacatalog.v1beta1.Tag, com.google.cloud.datacatalog.v1beta1.Tag.Builder, com.google.cloud.datacatalog.v1beta1.TagOrBuilder> tagBuilder_; /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tag field is set. */ public boolean hasTag() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tag. */ public com.google.cloud.datacatalog.v1beta1.Tag getTag() { if (tagBuilder_ == null) { return tag_ == null ? com.google.cloud.datacatalog.v1beta1.Tag.getDefaultInstance() : tag_; } else { return tagBuilder_.getMessage(); } } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTag(com.google.cloud.datacatalog.v1beta1.Tag value) { if (tagBuilder_ == null) { if (value == null) { throw new NullPointerException(); } tag_ = value; } else { tagBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTag(com.google.cloud.datacatalog.v1beta1.Tag.Builder builderForValue) { if (tagBuilder_ == null) { tag_ = builderForValue.build(); } else { tagBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeTag(com.google.cloud.datacatalog.v1beta1.Tag value) { if (tagBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && tag_ != null && tag_ != com.google.cloud.datacatalog.v1beta1.Tag.getDefaultInstance()) { getTagBuilder().mergeFrom(value); } else { tag_ = value; } } else { tagBuilder_.mergeFrom(value); } if (tag_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearTag() { bitField0_ = (bitField0_ & ~0x00000001); tag_ = null; if (tagBuilder_ != null) { tagBuilder_.dispose(); tagBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.datacatalog.v1beta1.Tag.Builder getTagBuilder() { bitField0_ |= 0x00000001; onChanged(); return getTagFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.datacatalog.v1beta1.TagOrBuilder getTagOrBuilder() { if (tagBuilder_ != null) { return tagBuilder_.getMessageOrBuilder(); } else { return tag_ == null ? com.google.cloud.datacatalog.v1beta1.Tag.getDefaultInstance() : tag_; } } /** * * * <pre> * Required. The updated tag. The "name" field must be set. * </pre> * * <code> * .google.cloud.datacatalog.v1beta1.Tag tag = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datacatalog.v1beta1.Tag, com.google.cloud.datacatalog.v1beta1.Tag.Builder, com.google.cloud.datacatalog.v1beta1.TagOrBuilder> getTagFieldBuilder() { if (tagBuilder_ == null) { tagBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datacatalog.v1beta1.Tag, com.google.cloud.datacatalog.v1beta1.Tag.Builder, com.google.cloud.datacatalog.v1beta1.TagOrBuilder>( getTag(), getParentForChildren(), isClean()); tag_ = null; } return tagBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Note: Currently, this parameter can only take `"fields"` as value. * * Names of fields whose values to overwrite on a tag. Currently, a tag has * the only modifiable field with the name `fields`. * * In general, if this parameter is absent or empty, all modifiable fields * are overwritten. If such fields are non-required and omitted in the * request body, their values are emptied. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datacatalog.v1beta1.UpdateTagRequest) } // @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1beta1.UpdateTagRequest) private static final com.google.cloud.datacatalog.v1beta1.UpdateTagRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1beta1.UpdateTagRequest(); } public static com.google.cloud.datacatalog.v1beta1.UpdateTagRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateTagRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateTagRequest>() { @java.lang.Override public UpdateTagRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UpdateTagRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateTagRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTagRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ignite-3
36,674
modules/compute/src/test/java/org/apache/ignite/internal/compute/ComputeComponentImplTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.compute; import static java.util.UUID.randomUUID; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.apache.ignite.compute.JobStatus.CANCELED; import static org.apache.ignite.compute.JobStatus.COMPLETED; import static org.apache.ignite.compute.JobStatus.EXECUTING; import static org.apache.ignite.compute.JobStatus.QUEUED; import static org.apache.ignite.internal.compute.ExecutionOptions.DEFAULT; import static org.apache.ignite.internal.testframework.matchers.CompletableFutureExceptionMatcher.willThrow; import static org.apache.ignite.internal.testframework.matchers.CompletableFutureExceptionMatcher.willThrowWithCauseOrSuppressed; import static org.apache.ignite.internal.testframework.matchers.CompletableFutureMatcher.willBe; import static org.apache.ignite.internal.testframework.matchers.CompletableFutureMatcher.willCompleteSuccessfully; import static org.apache.ignite.internal.testframework.matchers.CompletableFutureMatcher.willSucceedFast; import static org.apache.ignite.internal.testframework.matchers.JobStateMatcher.jobStateWithStatus; import static org.apache.ignite.internal.util.CompletableFutures.nullCompletedFuture; import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.mockito.Answers.RETURNS_DEEP_STUBS; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.ignite.Ignite; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.compute.JobExecution; import org.apache.ignite.compute.JobExecutionContext; import org.apache.ignite.compute.JobStatus; import org.apache.ignite.deployment.DeploymentUnit; import org.apache.ignite.deployment.version.Version; import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyService; import org.apache.ignite.internal.compute.configuration.ComputeConfiguration; import org.apache.ignite.internal.compute.events.ComputeEventMetadata; import org.apache.ignite.internal.compute.executor.ComputeExecutor; import org.apache.ignite.internal.compute.executor.ComputeExecutorImpl; import org.apache.ignite.internal.compute.loader.JobClassLoader; import org.apache.ignite.internal.compute.loader.JobContext; import org.apache.ignite.internal.compute.loader.JobContextManager; import org.apache.ignite.internal.compute.message.ExecuteRequest; import org.apache.ignite.internal.compute.message.ExecuteResponse; import org.apache.ignite.internal.compute.message.JobCancelRequest; import org.apache.ignite.internal.compute.message.JobCancelResponse; import org.apache.ignite.internal.compute.message.JobChangePriorityRequest; import org.apache.ignite.internal.compute.message.JobChangePriorityResponse; import org.apache.ignite.internal.compute.message.JobResultRequest; import org.apache.ignite.internal.compute.message.JobResultResponse; import org.apache.ignite.internal.compute.message.JobStateRequest; import org.apache.ignite.internal.compute.message.JobStateResponse; import org.apache.ignite.internal.compute.state.InMemoryComputeStateMachine; import org.apache.ignite.internal.configuration.testframework.ConfigurationExtension; import org.apache.ignite.internal.configuration.testframework.InjectConfiguration; import org.apache.ignite.internal.deployunit.DeploymentStatus; import org.apache.ignite.internal.deployunit.exception.DeploymentUnitNotFoundException; import org.apache.ignite.internal.deployunit.exception.DeploymentUnitUnavailableException; import org.apache.ignite.internal.eventlog.api.EventLog; import org.apache.ignite.internal.hlc.HybridClockImpl; import org.apache.ignite.internal.hlc.TestClockService; import org.apache.ignite.internal.lang.IgniteInternalException; import org.apache.ignite.internal.lang.NodeStoppingException; import org.apache.ignite.internal.manager.ComponentContext; import org.apache.ignite.internal.network.ClusterNodeImpl; import org.apache.ignite.internal.network.InternalClusterNode; import org.apache.ignite.internal.network.MessagingService; import org.apache.ignite.internal.network.NetworkMessage; import org.apache.ignite.internal.network.NetworkMessageHandler; import org.apache.ignite.internal.network.TopologyService; import org.apache.ignite.internal.testframework.BaseIgniteAbstractTest; import org.apache.ignite.internal.thread.IgniteThread; import org.apache.ignite.lang.CancelHandle; import org.apache.ignite.lang.CancellationToken; import org.apache.ignite.network.NetworkAddress; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) @ExtendWith(ConfigurationExtension.class) @Timeout(10) class ComputeComponentImplTest extends BaseIgniteAbstractTest { private static final String INSTANCE_NAME = "Ignite-0"; @Mock private Ignite ignite; @Mock private MessagingService messagingService; @Mock(answer = RETURNS_DEEP_STUBS) private TopologyService topologyService; @Mock private LogicalTopologyService logicalTopologyService; @InjectConfiguration("mock{threadPoolSize=1}") private ComputeConfiguration computeConfiguration; @Mock private JobContextManager jobContextManager; private ComputeComponent computeComponent; private final InternalClusterNode testNode = new ClusterNodeImpl(randomUUID(), "test", new NetworkAddress("test-host", 1)); private final InternalClusterNode remoteNode = new ClusterNodeImpl( randomUUID(), "remote", new NetworkAddress("remote-host", 1) ); private final AtomicReference<NetworkMessageHandler> computeMessageHandlerRef = new AtomicReference<>(); @BeforeEach void setUp() { lenient().when(ignite.name()).thenReturn(INSTANCE_NAME); lenient().when(topologyService.localMember().name()).thenReturn(INSTANCE_NAME); JobClassLoader classLoader = new JobClassLoader(List.of(), getClass().getClassLoader()); JobContext jobContext = new JobContext(classLoader, ignored -> {}); lenient().when(jobContextManager.acquireClassLoader(anyList())) .thenReturn(completedFuture(jobContext)); doAnswer(invocation -> { computeMessageHandlerRef.set(invocation.getArgument(1)); return null; }).when(messagingService).addMessageHandler(eq(ComputeMessageTypes.class), any()); InMemoryComputeStateMachine stateMachine = new InMemoryComputeStateMachine(computeConfiguration, INSTANCE_NAME); ComputeExecutor computeExecutor = new ComputeExecutorImpl( ignite, stateMachine, computeConfiguration, topologyService, new TestClockService(new HybridClockImpl()), EventLog.NOOP); computeComponent = new ComputeComponentImpl( INSTANCE_NAME, messagingService, topologyService, logicalTopologyService, jobContextManager, computeExecutor, computeConfiguration, EventLog.NOOP ); assertThat(computeComponent.startAsync(new ComponentContext()), willCompleteSuccessfully()); assertThat(computeMessageHandlerRef.get(), is(notNullValue())); } @AfterEach void cleanup() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); } @Test void executesLocally() { CancelHandle cancelHandle = CancelHandle.create(); JobExecution<ComputeJobDataHolder> execution = executeLocally( SimpleJob.class.getName(), cancelHandle.token() ); assertThat(unwrapResult(execution), willBe("jobResponse")); assertThat(execution.stateAsync(), willBe(jobStateWithStatus(COMPLETED))); assertThat(cancelHandle.cancelAsync(), willCompleteSuccessfully()); assertThat(execution.changePriorityAsync(1), willBe(false)); assertThatNoRequestsWereSent(); } @Test void testLongPreExecutionInitialization() { CompletableFuture<?> infiniteFuture = new CompletableFuture<>(); doReturn(infiniteFuture) .when(jobContextManager).acquireClassLoader(List.of()); CancelHandle cancelHandle = CancelHandle.create(); CompletableFuture<CancellableJobExecution<ComputeJobDataHolder>> executionFut = computeComponent.executeLocally( new ExecutionContext(DEFAULT, List.of(), SimpleJob.class.getName(), ComputeEventMetadata.builder(), null), cancelHandle.token() ); assertFalse(infiniteFuture.isDone()); assertFalse(executionFut.isDone()); cancelHandle.cancel(); assertThat(cancelHandle.cancelAsync(), willSucceedFast()); assertThat(infiniteFuture.isCompletedExceptionally(), is(true)); assertThat(executionFut.isCompletedExceptionally(), is(true)); } @Test void getsStateAndCancelsLocally() { CancelHandle cancelHandle = CancelHandle.create(); JobExecution<ComputeJobDataHolder> execution = executeLocally(LongJob.class.getName(), cancelHandle.token()); await().until(execution::stateAsync, willBe(jobStateWithStatus(EXECUTING))); assertThat(cancelHandle.cancelAsync(), willCompleteSuccessfully()); await().until(execution::stateAsync, willBe(jobStateWithStatus(CANCELED))); assertThatNoRequestsWereSent(); } @Test void stateCancelAndChangePriorityTriesLocalNodeFirst() { JobExecution<ComputeJobDataHolder> runningExecution = executeLocally(LongJob.class.getName(), null); await().until(runningExecution::stateAsync, willBe(jobStateWithStatus(EXECUTING))); JobExecution<ComputeJobDataHolder> queuedExecution = executeLocally(LongJob.class.getName(), null); await().until(queuedExecution::stateAsync, willBe(jobStateWithStatus(QUEUED))); UUID jobId = queuedExecution.idAsync().join(); assertThat(jobId, is(notNullValue())); assertThat(computeComponent.stateAsync(jobId), willBe(jobStateWithStatus(QUEUED))); assertThat(computeComponent.changePriorityAsync(jobId, 1), willBe(true)); assertThat(computeComponent.cancelAsync(jobId), willBe(true)); await().until(queuedExecution::stateAsync, willBe(jobStateWithStatus(CANCELED))); assertThatNoRequestsWereSent(); } private void assertThatNoRequestsWereSent() { verify(messagingService, never()).invoke(anyString(), any(), anyLong()); } @Test void executesLocallyWithException() { ExecutionException ex = assertThrows( ExecutionException.class, () -> executeLocally(FailingJob.class.getName()).get() ); assertThat(ex.getCause(), is(instanceOf(JobException.class))); assertThat(ex.getCause().getMessage(), is("Oops")); assertThat(ex.getCause().getCause(), is(notNullValue())); } @Test void executesRemotelyUsingNetworkCommunication() { UUID jobId = randomUUID(); respondWithExecuteResponseWhenExecuteRequestIsSent(jobId); respondWithJobResultResponseWhenJobResultRequestIsSent(jobId); respondWithJobStateResponseWhenJobStateRequestIsSent(jobId, COMPLETED); respondWithJobCancelResponseWhenJobCancelRequestIsSent(jobId, false); CancelHandle cancelHandle = CancelHandle.create(); JobExecution<ComputeJobDataHolder> execution = executeRemotely(SimpleJob.class.getName(), SharedComputeUtils.marshalArgOrResult("a", null), cancelHandle.token() ); assertThat(unwrapResult(execution), willBe("remoteResponse")); // Verify that second invocation of resultAsync will not result in the network communication (i.e. the result is cached locally) assertThat(unwrapResult(execution), willBe("remoteResponse")); assertThat(execution.stateAsync(), willBe(jobStateWithStatus(COMPLETED))); assertThat(cancelHandle.cancelAsync(), willCompleteSuccessfully()); assertThatExecuteRequestWasSent(SimpleJob.class.getName(), "a"); assertThatJobResultRequestWasSent(jobId); assertThatJobStateRequestWasSent(jobId); assertThatJobCancelRequestWasSent(jobId); } @Test void getsStateAndCancelsRemotelyUsingNetworkCommunication() { UUID jobId = randomUUID(); respondWithExecuteResponseWhenExecuteRequestIsSent(jobId); respondWithJobResultResponseWhenJobResultRequestIsSent(jobId); respondWithJobStateResponseWhenJobStateRequestIsSent(jobId, EXECUTING); respondWithJobCancelResponseWhenJobCancelRequestIsSent(jobId, true); CancelHandle cancelHandle = CancelHandle.create(); JobExecution<ComputeJobDataHolder> execution = executeRemotely(LongJob.class.getName(), null, cancelHandle.token()); assertThat(execution.stateAsync(), willBe(jobStateWithStatus(EXECUTING))); assertThat(unwrapResult(execution), willBe("remoteResponse")); assertThat(cancelHandle.cancelAsync(), willCompleteSuccessfully()); assertThatExecuteRequestWasSent(LongJob.class.getName(), null); assertThatJobResultRequestWasSent(jobId); assertThatJobStateRequestWasSent(jobId); assertThatJobCancelRequestWasSent(jobId); } @Test void changePriorityRemotelyUsingNetworkCommunication() { UUID jobId = randomUUID(); respondWithExecuteResponseWhenExecuteRequestIsSent(jobId); respondWithJobResultResponseWhenJobResultRequestIsSent(jobId); respondWithJobChangePriorityResponseWhenJobChangePriorityRequestIsSent(jobId); JobExecution<ComputeJobDataHolder> execution = executeRemotely(LongJob.class.getName(), null, null); assertThat(execution.changePriorityAsync(1), willBe(true)); assertThatJobChangePriorityRequestWasSent(jobId); } private void respondWithExecuteResponseWhenExecuteRequestIsSent(UUID jobId) { ExecuteResponse executeResponse = new ComputeMessagesFactory().executeResponse() .jobId(jobId) .build(); when(messagingService.invoke(anyString(), any(ExecuteRequest.class), anyLong())) .thenReturn(completedFuture(executeResponse)); } private void respondWithJobResultResponseWhenJobResultRequestIsSent(UUID jobId) { JobResultResponse jobResultResponse = new ComputeMessagesFactory().jobResultResponse() .result(SharedComputeUtils.marshalArgOrResult("remoteResponse", null)) .build(); when(messagingService.invoke(anyString(), argThat(msg -> jobResultRequestWithJobId(msg, jobId)), anyLong())) .thenReturn(completedFuture(jobResultResponse)); } private void respondWithJobStateResponseWhenJobStateRequestIsSent(UUID jobId, JobStatus status) { JobStateResponse jobStateResponse = new ComputeMessagesFactory().jobStateResponse() .state(JobStateImpl.builder().id(jobId).status(status).createTime(Instant.now()).build()) .build(); when(messagingService.invoke(anyString(), argThat(msg -> jobStateRequestWithJobId(msg, jobId)), anyLong())) .thenReturn(completedFuture(jobStateResponse)); } private void respondWithJobCancelResponseWhenJobCancelRequestIsSent(UUID jobId, boolean result) { JobCancelResponse jobCancelResponse = new ComputeMessagesFactory().jobCancelResponse() .result(result) .build(); when(messagingService.invoke(anyString(), argThat(msg -> jobCancelRequestWithJobId(msg, jobId)), anyLong())) .thenReturn(completedFuture(jobCancelResponse)); } private void respondWithJobChangePriorityResponseWhenJobChangePriorityRequestIsSent(UUID jobId) { JobChangePriorityResponse jobChangePriorityResponse = new ComputeMessagesFactory().jobChangePriorityResponse() .result(true) .build(); when(messagingService.invoke(anyString(), argThat(msg -> jobChangePriorityRequestWithJobId(msg, jobId)), anyLong())) .thenReturn(completedFuture(jobChangePriorityResponse)); } private static boolean jobResultRequestWithJobId(NetworkMessage argument, UUID jobId) { if (argument instanceof JobResultRequest) { JobResultRequest jobResultRequest = (JobResultRequest) argument; return jobResultRequest.jobId() == jobId; } return false; } private static boolean jobStateRequestWithJobId(NetworkMessage argument, UUID jobId) { if (argument instanceof JobStateRequest) { JobStateRequest jobStateRequest = (JobStateRequest) argument; return jobStateRequest.jobId() == jobId; } return false; } private static boolean jobCancelRequestWithJobId(NetworkMessage argument, UUID jobId) { if (argument instanceof JobCancelRequest) { JobCancelRequest jobCancelRequest = (JobCancelRequest) argument; return jobCancelRequest.jobId() == jobId; } return false; } private static boolean jobChangePriorityRequestWithJobId(NetworkMessage argument, UUID jobId) { if (argument instanceof JobChangePriorityRequest) { JobChangePriorityRequest jobChangePriorityRequest = (JobChangePriorityRequest) argument; return jobChangePriorityRequest.jobId() == jobId; } return false; } private void assertThatExecuteRequestWasSent(String jobClassName, @Nullable String arg) { ExecuteRequest capturedRequest = invokeAndCaptureRequest(ExecuteRequest.class); assertThat(capturedRequest.jobClassName(), is(jobClassName)); assertThat(SharedComputeUtils.unmarshalArgOrResult(capturedRequest.input(), null, null), is(equalTo(arg))); } private void assertThatJobResultRequestWasSent(UUID jobId) { JobResultRequest capturedRequest = invokeAndCaptureRequest(JobResultRequest.class); assertThat(capturedRequest.jobId(), is(jobId)); } private void assertThatJobStateRequestWasSent(UUID jobId) { JobStateRequest capturedRequest = invokeAndCaptureRequest(JobStateRequest.class); assertThat(capturedRequest.jobId(), is(jobId)); } private void assertThatJobCancelRequestWasSent(UUID jobId) { JobCancelRequest capturedRequest = invokeAndCaptureRequest(JobCancelRequest.class); assertThat(capturedRequest.jobId(), is(jobId)); } private void assertThatJobChangePriorityRequestWasSent(UUID jobId) { JobChangePriorityRequest capturedRequest = invokeAndCaptureRequest(JobChangePriorityRequest.class); assertThat(capturedRequest.jobId(), is(jobId)); } @Test void executesRemotelyWithException() { UUID jobId = randomUUID(); respondWithExecuteResponseWhenExecuteRequestIsSent(jobId); JobResultResponse jobResultResponse = new ComputeMessagesFactory().jobResultResponse() .throwable(new JobException("Oops", new Exception())) .build(); when(messagingService.invoke(anyString(), argThat(msg -> jobResultRequestWithJobId(msg, jobId)), anyLong())) .thenReturn(completedFuture(jobResultResponse)); ExecutionException ex = assertThrows( ExecutionException.class, () -> executeRemotely(FailingJob.class.getName()).get() ); assertThatExecuteRequestWasSent(FailingJob.class.getName(), null); assertThat(ex.getCause(), is(instanceOf(JobException.class))); assertThat(ex.getCause().getMessage(), is("Oops")); assertThat(ex.getCause().getCause(), is(notNullValue())); } @Test void executesJobAndRespondsWhenGetsExecuteRequest() { ExecuteRequest executeRequest = new ComputeMessagesFactory().executeRequest() .executeOptions(DEFAULT) .deploymentUnits(List.of()) .jobClassName(SimpleJob.class.getName()) .input(SharedComputeUtils.marshalArgOrResult("", null)) .build(); ExecuteResponse executeResponse = sendRequestAndCaptureResponse(executeRequest, testNode, 123L); UUID jobId = executeResponse.jobId(); assertThat(jobId, is(notNullValue())); assertThat(executeResponse.throwable(), is(nullValue())); JobResultRequest jobResultRequest = new ComputeMessagesFactory().jobResultRequest() .jobId(jobId) .build(); JobResultResponse jobResultResponse = sendRequestAndCaptureResponse(jobResultRequest, testNode, 456L); assertThat(SharedComputeUtils.unmarshalArgOrResult(jobResultResponse.result(), null, null), is("jobResponse")); assertThat(jobResultResponse.throwable(), is(nullValue())); } @Test void stoppedComponentReturnsExceptionOnLocalExecutionAttempt() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); CompletableFuture<String> result = executeLocally(SimpleJob.class.getName()); assertThat(result, willThrowWithCauseOrSuppressed(NodeStoppingException.class)); } @Test void localExecutionReleasesStopLock() throws Exception { executeLocally(SimpleJob.class.getName()).get(); assertTimeoutPreemptively( Duration.ofSeconds(3), () -> assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()) ); } @Test void stoppedComponentReturnsExceptionOnRemoteExecutionAttempt() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); CompletableFuture<String> result = executeRemotely(SimpleJob.class.getName()); assertThat(result, willThrowWithCauseOrSuppressed(NodeStoppingException.class)); } @Test void remoteExecutionReleasesStopLock() throws Exception { UUID jobId = randomUUID(); respondWithExecuteResponseWhenExecuteRequestIsSent(jobId); respondWithJobResultResponseWhenJobResultRequestIsSent(jobId); executeRemotely(SimpleJob.class.getName()).get(); assertTimeoutPreemptively( Duration.ofSeconds(3), () -> assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()) ); } @Test void stoppedComponentReturnsExceptionOnExecuteRequestAttempt() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); ExecuteRequest request = new ComputeMessagesFactory().executeRequest() .executeOptions(DEFAULT) .deploymentUnits(List.of()) .jobClassName(SimpleJob.class.getName()) .input(SharedComputeUtils.marshalArgOrResult(42, null)) .build(); ExecuteResponse response = sendRequestAndCaptureResponse(request, testNode, 123L); assertThat(response.jobId(), is(nullValue())); assertThat(response.throwable(), is(instanceOf(IgniteInternalException.class))); assertThat(response.throwable().getCause(), is(instanceOf(NodeStoppingException.class))); } @Test void stoppedComponentReturnsExceptionOnJobResultRequestAttempt() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); JobResultRequest jobResultRequest = new ComputeMessagesFactory().jobResultRequest() .jobId(randomUUID()) .build(); JobResultResponse response = sendRequestAndCaptureResponse(jobResultRequest, testNode, 123L); assertThat(response.result(), is(nullValue())); assertThat(response.throwable(), is(instanceOf(IgniteInternalException.class))); assertThat(response.throwable().getCause(), is(instanceOf(NodeStoppingException.class))); } @Test void stoppedComponentReturnsExceptionOnJobStateRequestAttempt() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); JobStateRequest jobStateRequest = new ComputeMessagesFactory().jobStateRequest() .jobId(randomUUID()) .build(); JobStateResponse response = sendRequestAndCaptureResponse(jobStateRequest, testNode, 123L); assertThat(response.state(), is(nullValue())); assertThat(response.throwable(), is(instanceOf(IgniteInternalException.class))); assertThat(response.throwable().getCause(), is(instanceOf(NodeStoppingException.class))); } @Test void stoppedComponentReturnsExceptionOnJobCancelRequestAttempt() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); JobCancelRequest jobCancelRequest = new ComputeMessagesFactory().jobCancelRequest() .jobId(randomUUID()) .build(); JobCancelResponse response = sendRequestAndCaptureResponse(jobCancelRequest, testNode, 123L); assertThat(response.result(), is(nullValue())); assertThat(response.throwable(), is(instanceOf(IgniteInternalException.class))); assertThat(response.throwable().getCause(), is(instanceOf(NodeStoppingException.class))); } @Test void stoppedComponentReturnsExceptionOnJobChangePriorityRequestAttempt() { assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); JobChangePriorityRequest jobChangePriorityRequest = new ComputeMessagesFactory().jobChangePriorityRequest() .jobId(randomUUID()) .priority(1) .build(); JobChangePriorityResponse response = sendRequestAndCaptureResponse(jobChangePriorityRequest, testNode, 123L); assertThat(response.result(), is(nullValue())); assertThat(response.throwable(), is(instanceOf(IgniteInternalException.class))); assertThat(response.throwable().getCause(), is(instanceOf(NodeStoppingException.class))); } @Test void executorThreadsAreNamedAccordingly() { assertThat( executeLocally(GetThreadNameJob.class.getName()), willBe(startsWith(IgniteThread.threadPrefix(INSTANCE_NAME, "compute"))) ); } @Test void stopCausesCancellationExceptionOnLocalExecution() { // take the only executor thread executeLocally(LongJob.class.getName()); // the corresponding task goes to work queue CompletableFuture<String> resultFuture = executeLocally(SimpleJob.class.getName()); assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); // now work queue is dropped to the floor, so the future should be resolved with a cancellation assertThat(resultFuture, willThrow(CancellationException.class)); } @Test void stopCausesCancellationExceptionOnRemoteExecution() { respondWithExecuteResponseWhenExecuteRequestIsSent(randomUUID()); respondWithIncompleteFutureWhenJobResultRequestIsSent(); CompletableFuture<String> resultFuture = executeRemotely(SimpleJob.class.getName()); assertThat(computeComponent.stopAsync(new ComponentContext()), willCompleteSuccessfully()); assertThat(resultFuture, willThrow(CancellationException.class)); } private void respondWithIncompleteFutureWhenJobResultRequestIsSent() { when(messagingService.invoke(anyString(), any(JobResultRequest.class), anyLong())) .thenReturn(new CompletableFuture<>()); } @Test void executionOfJobOfNonExistentClassResultsInException() { assertThat( executeLocally("no-such-class"), willThrow(Exception.class, "Cannot load job class by name 'no-such-class'") ); } @Test void executionOfNonJobClassResultsInException() { assertThat( executeLocally(Object.class.getName()), willThrow(Exception.class, "'java.lang.Object' does not implement ComputeJob interface") ); } @Test void executionOfNotExistingDeployedUnit() { List<DeploymentUnit> units = List.of(new DeploymentUnit("unit", "1.0.0")); doReturn(CompletableFuture.failedFuture(new DeploymentUnitNotFoundException("unit", Version.parseVersion("1.0.0")))) .when(jobContextManager).acquireClassLoader(units); assertThat( executeLocally(units, "com.example.Maim"), willThrow(ClassNotFoundException.class) ); } @Test void executionOfNotAvailableDeployedUnit() { List<DeploymentUnit> units = List.of(new DeploymentUnit("unit", "1.0.0")); DeploymentUnitUnavailableException toBeThrown = new DeploymentUnitUnavailableException( "unit", Version.parseVersion("1.0.0"), DeploymentStatus.OBSOLETE, DeploymentStatus.REMOVING ); doReturn(CompletableFuture.failedFuture(toBeThrown)) .when(jobContextManager).acquireClassLoader(units); assertThat( executeLocally(units, "com.example.Maim"), willThrow(ClassNotFoundException.class) ); } private <T extends NetworkMessage> T invokeAndCaptureRequest(Class<T> clazz) { ArgumentCaptor<T> requestCaptor = ArgumentCaptor.forClass(clazz); verify(messagingService).invoke(eq(remoteNode.name()), requestCaptor.capture(), anyLong()); return requestCaptor.getValue(); } private <T extends NetworkMessage> T sendRequestAndCaptureResponse( NetworkMessage request, InternalClusterNode sender, long correlationId ) { AtomicBoolean responseSent = new AtomicBoolean(false); when(messagingService.respond(eq(sender.name()), any(), eq(correlationId))) .thenAnswer(invocation -> { responseSent.set(true); return nullCompletedFuture(); }); computeMessageHandlerRef.get().onReceived(request, testNode, correlationId); await().until(responseSent::get, is(true)); ArgumentCaptor<T> responseCaptor = ArgumentCaptor.captor(); verify(messagingService).respond(eq(sender.name()), responseCaptor.capture(), eq(correlationId)); return responseCaptor.getValue(); } private CompletableFuture<String> executeLocally(String jobClassName) { return executeLocally(List.of(), jobClassName); } private CompletableFuture<String> executeLocally(List<DeploymentUnit> units, String jobClassName) { return computeComponent.executeLocally( new ExecutionContext(DEFAULT, units, jobClassName, ComputeEventMetadata.builder(), null), null ).thenCompose(ComputeComponentImplTest::unwrapResult); } private JobExecution<ComputeJobDataHolder> executeLocally(String jobClassName, @Nullable CancellationToken cancellationToken) { CompletableFuture<CancellableJobExecution<ComputeJobDataHolder>> executionFut = computeComponent.executeLocally( new ExecutionContext(DEFAULT, List.of(), jobClassName, ComputeEventMetadata.builder(), null), cancellationToken ); assertThat(executionFut, willCompleteSuccessfully()); return executionFut.join(); } private JobExecution<ComputeJobDataHolder> executeRemotely( String jobClassName, @Nullable ComputeJobDataHolder arg, @Nullable CancellationToken cancellationToken ) { CompletableFuture<CancellableJobExecution<ComputeJobDataHolder>> executionFut = computeComponent.executeRemotely( remoteNode, new ExecutionContext(DEFAULT, List.of(), jobClassName, ComputeEventMetadata.builder(), arg), cancellationToken ); assertThat(executionFut, willCompleteSuccessfully()); return executionFut.join(); } private CompletableFuture<String> executeRemotely(String jobClassName) { return computeComponent.executeRemotely( remoteNode, new ExecutionContext(DEFAULT, List.of(), jobClassName, ComputeEventMetadata.builder(), null), null ).thenCompose(ComputeComponentImplTest::unwrapResult); } private static CompletableFuture<String> unwrapResult(JobExecution<ComputeJobDataHolder> execution) { return execution.resultAsync().thenApply(r -> SharedComputeUtils.unmarshalArgOrResult(r, null, null)); } private static class SimpleJob implements ComputeJob<String, String> { /** {@inheritDoc} */ @Override public CompletableFuture<String> executeAsync(JobExecutionContext context, String args) { return completedFuture("jobResponse"); } } private static class FailingJob implements ComputeJob<String, String> { /** {@inheritDoc} */ @Override public CompletableFuture<String> executeAsync(JobExecutionContext context, String args) { throw new JobException("Oops", new Exception()); } } private static class JobException extends RuntimeException { private JobException(String message, Throwable cause) { super(message, cause); } } private static class GetThreadNameJob implements ComputeJob<String, String> { /** {@inheritDoc} */ @Override public CompletableFuture<String> executeAsync(JobExecutionContext context, String args) { return completedFuture(Thread.currentThread().getName()); } } private static class LongJob implements ComputeJob<Void, String> { /** {@inheritDoc} */ @Override public @Nullable CompletableFuture<String> executeAsync(JobExecutionContext context, Void args) { try { Thread.sleep(1_000_000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return null; } } }
apache/kafka
36,636
clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.protocol; import org.apache.kafka.common.InvalidRecordException; import org.apache.kafka.common.errors.ApiException; import org.apache.kafka.common.errors.BrokerIdNotRegisteredException; import org.apache.kafka.common.errors.BrokerNotAvailableException; import org.apache.kafka.common.errors.ClusterAuthorizationException; import org.apache.kafka.common.errors.ConcurrentTransactionsException; import org.apache.kafka.common.errors.ControllerMovedException; import org.apache.kafka.common.errors.CoordinatorLoadInProgressException; import org.apache.kafka.common.errors.CoordinatorNotAvailableException; import org.apache.kafka.common.errors.CorruptRecordException; import org.apache.kafka.common.errors.DelegationTokenAuthorizationException; import org.apache.kafka.common.errors.DelegationTokenDisabledException; import org.apache.kafka.common.errors.DelegationTokenExpiredException; import org.apache.kafka.common.errors.DelegationTokenNotFoundException; import org.apache.kafka.common.errors.DelegationTokenOwnerMismatchException; import org.apache.kafka.common.errors.DuplicateBrokerRegistrationException; import org.apache.kafka.common.errors.DuplicateResourceException; import org.apache.kafka.common.errors.DuplicateSequenceException; import org.apache.kafka.common.errors.DuplicateVoterException; import org.apache.kafka.common.errors.ElectionNotNeededException; import org.apache.kafka.common.errors.EligibleLeadersNotAvailableException; import org.apache.kafka.common.errors.FeatureUpdateFailedException; import org.apache.kafka.common.errors.FencedInstanceIdException; import org.apache.kafka.common.errors.FencedLeaderEpochException; import org.apache.kafka.common.errors.FencedMemberEpochException; import org.apache.kafka.common.errors.FencedStateEpochException; import org.apache.kafka.common.errors.FetchSessionIdNotFoundException; import org.apache.kafka.common.errors.FetchSessionTopicIdException; import org.apache.kafka.common.errors.GroupAuthorizationException; import org.apache.kafka.common.errors.GroupIdNotFoundException; import org.apache.kafka.common.errors.GroupMaxSizeReachedException; import org.apache.kafka.common.errors.GroupNotEmptyException; import org.apache.kafka.common.errors.GroupSubscribedToTopicException; import org.apache.kafka.common.errors.IllegalGenerationException; import org.apache.kafka.common.errors.IllegalSaslStateException; import org.apache.kafka.common.errors.InconsistentClusterIdException; import org.apache.kafka.common.errors.InconsistentGroupProtocolException; import org.apache.kafka.common.errors.InconsistentTopicIdException; import org.apache.kafka.common.errors.InconsistentVoterSetException; import org.apache.kafka.common.errors.IneligibleReplicaException; import org.apache.kafka.common.errors.InvalidCommitOffsetSizeException; import org.apache.kafka.common.errors.InvalidConfigurationException; import org.apache.kafka.common.errors.InvalidFetchSessionEpochException; import org.apache.kafka.common.errors.InvalidFetchSizeException; import org.apache.kafka.common.errors.InvalidGroupIdException; import org.apache.kafka.common.errors.InvalidPartitionsException; import org.apache.kafka.common.errors.InvalidPidMappingException; import org.apache.kafka.common.errors.InvalidPrincipalTypeException; import org.apache.kafka.common.errors.InvalidProducerEpochException; import org.apache.kafka.common.errors.InvalidRecordStateException; import org.apache.kafka.common.errors.InvalidRegistrationException; import org.apache.kafka.common.errors.InvalidRegularExpression; import org.apache.kafka.common.errors.InvalidReplicaAssignmentException; import org.apache.kafka.common.errors.InvalidReplicationFactorException; import org.apache.kafka.common.errors.InvalidRequestException; import org.apache.kafka.common.errors.InvalidRequiredAcksException; import org.apache.kafka.common.errors.InvalidSessionTimeoutException; import org.apache.kafka.common.errors.InvalidShareSessionEpochException; import org.apache.kafka.common.errors.InvalidTimestampException; import org.apache.kafka.common.errors.InvalidTopicException; import org.apache.kafka.common.errors.InvalidTxnStateException; import org.apache.kafka.common.errors.InvalidTxnTimeoutException; import org.apache.kafka.common.errors.InvalidUpdateVersionException; import org.apache.kafka.common.errors.InvalidVoterKeyException; import org.apache.kafka.common.errors.KafkaStorageException; import org.apache.kafka.common.errors.LeaderNotAvailableException; import org.apache.kafka.common.errors.ListenerNotFoundException; import org.apache.kafka.common.errors.LogDirNotFoundException; import org.apache.kafka.common.errors.MemberIdRequiredException; import org.apache.kafka.common.errors.MismatchedEndpointTypeException; import org.apache.kafka.common.errors.NetworkException; import org.apache.kafka.common.errors.NewLeaderElectedException; import org.apache.kafka.common.errors.NoReassignmentInProgressException; import org.apache.kafka.common.errors.NotControllerException; import org.apache.kafka.common.errors.NotCoordinatorException; import org.apache.kafka.common.errors.NotEnoughReplicasAfterAppendException; import org.apache.kafka.common.errors.NotEnoughReplicasException; import org.apache.kafka.common.errors.NotLeaderOrFollowerException; import org.apache.kafka.common.errors.OffsetMetadataTooLarge; import org.apache.kafka.common.errors.OffsetMovedToTieredStorageException; import org.apache.kafka.common.errors.OffsetNotAvailableException; import org.apache.kafka.common.errors.OffsetOutOfRangeException; import org.apache.kafka.common.errors.OperationNotAttemptedException; import org.apache.kafka.common.errors.OutOfOrderSequenceException; import org.apache.kafka.common.errors.PolicyViolationException; import org.apache.kafka.common.errors.PositionOutOfRangeException; import org.apache.kafka.common.errors.PreferredLeaderNotAvailableException; import org.apache.kafka.common.errors.PrincipalDeserializationException; import org.apache.kafka.common.errors.ProducerFencedException; import org.apache.kafka.common.errors.ReassignmentInProgressException; import org.apache.kafka.common.errors.RebalanceInProgressException; import org.apache.kafka.common.errors.RebootstrapRequiredException; import org.apache.kafka.common.errors.RecordBatchTooLargeException; import org.apache.kafka.common.errors.RecordTooLargeException; import org.apache.kafka.common.errors.ReplicaNotAvailableException; import org.apache.kafka.common.errors.ResourceNotFoundException; import org.apache.kafka.common.errors.RetriableException; import org.apache.kafka.common.errors.SaslAuthenticationException; import org.apache.kafka.common.errors.SecurityDisabledException; import org.apache.kafka.common.errors.ShareSessionLimitReachedException; import org.apache.kafka.common.errors.ShareSessionNotFoundException; import org.apache.kafka.common.errors.SnapshotNotFoundException; import org.apache.kafka.common.errors.StaleBrokerEpochException; import org.apache.kafka.common.errors.StaleMemberEpochException; import org.apache.kafka.common.errors.StreamsInvalidTopologyEpochException; import org.apache.kafka.common.errors.StreamsInvalidTopologyException; import org.apache.kafka.common.errors.StreamsTopologyFencedException; import org.apache.kafka.common.errors.TelemetryTooLargeException; import org.apache.kafka.common.errors.ThrottlingQuotaExceededException; import org.apache.kafka.common.errors.TimeoutException; import org.apache.kafka.common.errors.TopicAuthorizationException; import org.apache.kafka.common.errors.TopicDeletionDisabledException; import org.apache.kafka.common.errors.TopicExistsException; import org.apache.kafka.common.errors.TransactionAbortableException; import org.apache.kafka.common.errors.TransactionCoordinatorFencedException; import org.apache.kafka.common.errors.TransactionalIdAuthorizationException; import org.apache.kafka.common.errors.TransactionalIdNotFoundException; import org.apache.kafka.common.errors.UnacceptableCredentialException; import org.apache.kafka.common.errors.UnknownControllerIdException; import org.apache.kafka.common.errors.UnknownLeaderEpochException; import org.apache.kafka.common.errors.UnknownMemberIdException; import org.apache.kafka.common.errors.UnknownProducerIdException; import org.apache.kafka.common.errors.UnknownServerException; import org.apache.kafka.common.errors.UnknownSubscriptionIdException; import org.apache.kafka.common.errors.UnknownTopicIdException; import org.apache.kafka.common.errors.UnknownTopicOrPartitionException; import org.apache.kafka.common.errors.UnreleasedInstanceIdException; import org.apache.kafka.common.errors.UnstableOffsetCommitException; import org.apache.kafka.common.errors.UnsupportedAssignorException; import org.apache.kafka.common.errors.UnsupportedByAuthenticationException; import org.apache.kafka.common.errors.UnsupportedCompressionTypeException; import org.apache.kafka.common.errors.UnsupportedEndpointTypeException; import org.apache.kafka.common.errors.UnsupportedForMessageFormatException; import org.apache.kafka.common.errors.UnsupportedSaslMechanismException; import org.apache.kafka.common.errors.UnsupportedVersionException; import org.apache.kafka.common.errors.VoterNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.function.Function; /** * This class contains all the client-server errors--those errors that must be sent from the server to the client. These * are thus part of the protocol. The names can be changed but the error code cannot. * * Note that client library will convert an unknown error code to the non-retriable UnknownServerException if the client library * version is old and does not recognize the newly-added error code. Therefore when a new server-side error is added, * we may need extra logic to convert the new error code to another existing error code before sending the response back to * the client if the request version suggests that the client may not recognize the new error code. * * Do not add exceptions that occur only on the client or only on the server here. * * @see org.apache.kafka.common.network.SslTransportLayer */ public enum Errors { UNKNOWN_SERVER_ERROR(-1, "The server experienced an unexpected error when processing the request.", UnknownServerException::new), NONE(0, null, message -> null), OFFSET_OUT_OF_RANGE(1, "The requested offset is not within the range of offsets maintained by the server.", OffsetOutOfRangeException::new), CORRUPT_MESSAGE(2, "This message has failed its CRC checksum, exceeds the valid size, has a null key for a compacted topic, or is otherwise corrupt.", CorruptRecordException::new), UNKNOWN_TOPIC_OR_PARTITION(3, "This server does not host this topic-partition.", UnknownTopicOrPartitionException::new), INVALID_FETCH_SIZE(4, "The requested fetch size is invalid.", InvalidFetchSizeException::new), LEADER_NOT_AVAILABLE(5, "There is no leader for this topic-partition as we are in the middle of a leadership election.", LeaderNotAvailableException::new), NOT_LEADER_OR_FOLLOWER(6, "For requests intended only for the leader, this error indicates that the broker is not the current leader. " + "For requests intended for any replica, this error indicates that the broker is not a replica of the topic partition.", NotLeaderOrFollowerException::new), REQUEST_TIMED_OUT(7, "The request timed out.", TimeoutException::new), BROKER_NOT_AVAILABLE(8, "The broker is not available.", BrokerNotAvailableException::new), REPLICA_NOT_AVAILABLE(9, "The replica is not available for the requested topic-partition. Produce/Fetch requests and other requests " + "intended only for the leader or follower return NOT_LEADER_OR_FOLLOWER if the broker is not a replica of the topic-partition.", ReplicaNotAvailableException::new), MESSAGE_TOO_LARGE(10, "The request included a message larger than the max message size the server will accept.", RecordTooLargeException::new), STALE_CONTROLLER_EPOCH(11, "The controller moved to another broker.", ControllerMovedException::new), OFFSET_METADATA_TOO_LARGE(12, "The metadata field of the offset request was too large.", OffsetMetadataTooLarge::new), NETWORK_EXCEPTION(13, "The server disconnected before a response was received.", NetworkException::new), COORDINATOR_LOAD_IN_PROGRESS(14, "The coordinator is loading and hence can't process requests.", CoordinatorLoadInProgressException::new), COORDINATOR_NOT_AVAILABLE(15, "The coordinator is not available.", CoordinatorNotAvailableException::new), NOT_COORDINATOR(16, "This is not the correct coordinator.", NotCoordinatorException::new), INVALID_TOPIC_EXCEPTION(17, "The request attempted to perform an operation on an invalid topic.", InvalidTopicException::new), RECORD_LIST_TOO_LARGE(18, "The request included message batch larger than the configured segment size on the server.", RecordBatchTooLargeException::new), NOT_ENOUGH_REPLICAS(19, "Messages are rejected since there are fewer in-sync replicas than required.", NotEnoughReplicasException::new), NOT_ENOUGH_REPLICAS_AFTER_APPEND(20, "Messages are written to the log, but to fewer in-sync replicas than required.", NotEnoughReplicasAfterAppendException::new), INVALID_REQUIRED_ACKS(21, "Produce request specified an invalid value for required acks.", InvalidRequiredAcksException::new), ILLEGAL_GENERATION(22, "Specified group generation id is not valid.", IllegalGenerationException::new), INCONSISTENT_GROUP_PROTOCOL(23, "The group member's supported protocols are incompatible with those of existing members " + "or first group member tried to join with empty protocol type or empty protocol list.", InconsistentGroupProtocolException::new), INVALID_GROUP_ID(24, "The group id is invalid.", InvalidGroupIdException::new), UNKNOWN_MEMBER_ID(25, "The coordinator is not aware of this member.", UnknownMemberIdException::new), INVALID_SESSION_TIMEOUT(26, "The session timeout is not within the range allowed by the broker " + "(as configured by group.min.session.timeout.ms and group.max.session.timeout.ms).", InvalidSessionTimeoutException::new), REBALANCE_IN_PROGRESS(27, "The group is rebalancing, so a rejoin is needed.", RebalanceInProgressException::new), INVALID_COMMIT_OFFSET_SIZE(28, "The committing offset data size is not valid.", InvalidCommitOffsetSizeException::new), TOPIC_AUTHORIZATION_FAILED(29, "Topic authorization failed.", TopicAuthorizationException::new), GROUP_AUTHORIZATION_FAILED(30, "Group authorization failed.", GroupAuthorizationException::new), CLUSTER_AUTHORIZATION_FAILED(31, "Cluster authorization failed.", ClusterAuthorizationException::new), INVALID_TIMESTAMP(32, "The timestamp of the message is out of acceptable range.", InvalidTimestampException::new), UNSUPPORTED_SASL_MECHANISM(33, "The broker does not support the requested SASL mechanism.", UnsupportedSaslMechanismException::new), ILLEGAL_SASL_STATE(34, "Request is not valid given the current SASL state.", IllegalSaslStateException::new), UNSUPPORTED_VERSION(35, "The version of API is not supported.", UnsupportedVersionException::new), TOPIC_ALREADY_EXISTS(36, "Topic with this name already exists.", TopicExistsException::new), INVALID_PARTITIONS(37, "Number of partitions is below 1.", InvalidPartitionsException::new), INVALID_REPLICATION_FACTOR(38, "Replication factor is below 1 or larger than the number of available brokers.", InvalidReplicationFactorException::new), INVALID_REPLICA_ASSIGNMENT(39, "Replica assignment is invalid.", InvalidReplicaAssignmentException::new), INVALID_CONFIG(40, "Configuration is invalid.", InvalidConfigurationException::new), NOT_CONTROLLER(41, "This is not the correct controller for this cluster.", NotControllerException::new), INVALID_REQUEST(42, "This most likely occurs because of a request being malformed by the " + "client library or the message was sent to an incompatible broker. See the broker logs " + "for more details.", InvalidRequestException::new), UNSUPPORTED_FOR_MESSAGE_FORMAT(43, "The message format version on the broker does not support the request.", UnsupportedForMessageFormatException::new), POLICY_VIOLATION(44, "Request parameters do not satisfy the configured policy.", PolicyViolationException::new), OUT_OF_ORDER_SEQUENCE_NUMBER(45, "The broker received an out of order sequence number.", OutOfOrderSequenceException::new), DUPLICATE_SEQUENCE_NUMBER(46, "The broker received a duplicate sequence number.", DuplicateSequenceException::new), INVALID_PRODUCER_EPOCH(47, "Producer attempted to produce with an old epoch.", InvalidProducerEpochException::new), INVALID_TXN_STATE(48, "The producer attempted a transactional operation in an invalid state.", InvalidTxnStateException::new), INVALID_PRODUCER_ID_MAPPING(49, "The producer attempted to use a producer id which is not currently assigned to " + "its transactional id.", InvalidPidMappingException::new), INVALID_TRANSACTION_TIMEOUT(50, "The transaction timeout is larger than the maximum value allowed by " + "the broker (as configured by transaction.max.timeout.ms).", InvalidTxnTimeoutException::new), CONCURRENT_TRANSACTIONS(51, "The producer attempted to update a transaction " + "while another concurrent operation on the same transaction was ongoing.", ConcurrentTransactionsException::new), TRANSACTION_COORDINATOR_FENCED(52, "Indicates that the transaction coordinator sending a WriteTxnMarker " + "is no longer the current coordinator for a given producer.", TransactionCoordinatorFencedException::new), TRANSACTIONAL_ID_AUTHORIZATION_FAILED(53, "Transactional Id authorization failed.", TransactionalIdAuthorizationException::new), SECURITY_DISABLED(54, "Security features are disabled.", SecurityDisabledException::new), OPERATION_NOT_ATTEMPTED(55, "The broker did not attempt to execute this operation. This may happen for " + "batched RPCs where some operations in the batch failed, causing the broker to respond without " + "trying the rest.", OperationNotAttemptedException::new), KAFKA_STORAGE_ERROR(56, "Disk error when trying to access log file on the disk.", KafkaStorageException::new), LOG_DIR_NOT_FOUND(57, "The user-specified log directory is not found in the broker config.", LogDirNotFoundException::new), SASL_AUTHENTICATION_FAILED(58, "SASL Authentication failed.", SaslAuthenticationException::new), UNKNOWN_PRODUCER_ID(59, "This exception is raised by the broker if it could not locate the producer metadata " + "associated with the producerId in question. This could happen if, for instance, the producer's records " + "were deleted because their retention time had elapsed. Once the last records of the producerId are " + "removed, the producer's metadata is removed from the broker, and future appends by the producer will " + "return this exception.", UnknownProducerIdException::new), REASSIGNMENT_IN_PROGRESS(60, "A partition reassignment is in progress.", ReassignmentInProgressException::new), DELEGATION_TOKEN_AUTH_DISABLED(61, "Delegation Token feature is not enabled.", DelegationTokenDisabledException::new), DELEGATION_TOKEN_NOT_FOUND(62, "Delegation Token is not found on server.", DelegationTokenNotFoundException::new), DELEGATION_TOKEN_OWNER_MISMATCH(63, "Specified Principal is not valid Owner/Renewer.", DelegationTokenOwnerMismatchException::new), DELEGATION_TOKEN_REQUEST_NOT_ALLOWED(64, "Delegation Token requests are not allowed on PLAINTEXT/1-way SSL " + "channels and on delegation token authenticated channels.", UnsupportedByAuthenticationException::new), DELEGATION_TOKEN_AUTHORIZATION_FAILED(65, "Delegation Token authorization failed.", DelegationTokenAuthorizationException::new), DELEGATION_TOKEN_EXPIRED(66, "Delegation Token is expired.", DelegationTokenExpiredException::new), INVALID_PRINCIPAL_TYPE(67, "Supplied principalType is not supported.", InvalidPrincipalTypeException::new), NON_EMPTY_GROUP(68, "The group is not empty.", GroupNotEmptyException::new), GROUP_ID_NOT_FOUND(69, "The group id does not exist.", GroupIdNotFoundException::new), FETCH_SESSION_ID_NOT_FOUND(70, "The fetch session ID was not found.", FetchSessionIdNotFoundException::new), INVALID_FETCH_SESSION_EPOCH(71, "The fetch session epoch is invalid.", InvalidFetchSessionEpochException::new), LISTENER_NOT_FOUND(72, "There is no listener on the leader broker that matches the listener on which " + "metadata request was processed.", ListenerNotFoundException::new), TOPIC_DELETION_DISABLED(73, "Topic deletion is disabled.", TopicDeletionDisabledException::new), FENCED_LEADER_EPOCH(74, "The leader epoch in the request is older than the epoch on the broker.", FencedLeaderEpochException::new), UNKNOWN_LEADER_EPOCH(75, "The leader epoch in the request is newer than the epoch on the broker.", UnknownLeaderEpochException::new), UNSUPPORTED_COMPRESSION_TYPE(76, "The requesting client does not support the compression type of given partition.", UnsupportedCompressionTypeException::new), STALE_BROKER_EPOCH(77, "Broker epoch has changed.", StaleBrokerEpochException::new), OFFSET_NOT_AVAILABLE(78, "The leader high watermark has not caught up from a recent leader " + "election so the offsets cannot be guaranteed to be monotonically increasing.", OffsetNotAvailableException::new), MEMBER_ID_REQUIRED(79, "The group member needs to have a valid member id before actually entering a consumer group.", MemberIdRequiredException::new), PREFERRED_LEADER_NOT_AVAILABLE(80, "The preferred leader was not available.", PreferredLeaderNotAvailableException::new), GROUP_MAX_SIZE_REACHED(81, "The group has reached its maximum size.", GroupMaxSizeReachedException::new), FENCED_INSTANCE_ID(82, "The broker rejected this static consumer since " + "another consumer with the same group.instance.id has registered with a different member.id.", FencedInstanceIdException::new), ELIGIBLE_LEADERS_NOT_AVAILABLE(83, "Eligible topic partition leaders are not available.", EligibleLeadersNotAvailableException::new), ELECTION_NOT_NEEDED(84, "Leader election not needed for topic partition.", ElectionNotNeededException::new), NO_REASSIGNMENT_IN_PROGRESS(85, "No partition reassignment is in progress.", NoReassignmentInProgressException::new), GROUP_SUBSCRIBED_TO_TOPIC(86, "Deleting offsets of a topic is forbidden while the consumer group is actively subscribed to it.", GroupSubscribedToTopicException::new), INVALID_RECORD(87, "This record has failed the validation on broker and hence will be rejected.", InvalidRecordException::new), UNSTABLE_OFFSET_COMMIT(88, "There are unstable offsets that need to be cleared.", UnstableOffsetCommitException::new), THROTTLING_QUOTA_EXCEEDED(89, "The throttling quota has been exceeded.", ThrottlingQuotaExceededException::new), PRODUCER_FENCED(90, "There is a newer producer with the same transactionalId " + "which fences the current one.", ProducerFencedException::new), RESOURCE_NOT_FOUND(91, "A request illegally referred to a resource that does not exist.", ResourceNotFoundException::new), DUPLICATE_RESOURCE(92, "A request illegally referred to the same resource twice.", DuplicateResourceException::new), UNACCEPTABLE_CREDENTIAL(93, "Requested credential would not meet criteria for acceptability.", UnacceptableCredentialException::new), INCONSISTENT_VOTER_SET(94, "Indicates that the either the sender or recipient of a " + "voter-only request is not one of the expected voters.", InconsistentVoterSetException::new), INVALID_UPDATE_VERSION(95, "The given update version was invalid.", InvalidUpdateVersionException::new), FEATURE_UPDATE_FAILED(96, "Unable to update finalized features due to an unexpected server error.", FeatureUpdateFailedException::new), PRINCIPAL_DESERIALIZATION_FAILURE(97, "Request principal deserialization failed during forwarding. " + "This indicates an internal error on the broker cluster security setup.", PrincipalDeserializationException::new), SNAPSHOT_NOT_FOUND(98, "Requested snapshot was not found.", SnapshotNotFoundException::new), POSITION_OUT_OF_RANGE(99, "Requested position is not greater than or equal to zero, and less than the size of the snapshot.", PositionOutOfRangeException::new), UNKNOWN_TOPIC_ID(100, "This server does not host this topic ID.", UnknownTopicIdException::new), DUPLICATE_BROKER_REGISTRATION(101, "This broker ID is already in use.", DuplicateBrokerRegistrationException::new), BROKER_ID_NOT_REGISTERED(102, "The given broker ID was not registered.", BrokerIdNotRegisteredException::new), INCONSISTENT_TOPIC_ID(103, "The log's topic ID did not match the topic ID in the request.", InconsistentTopicIdException::new), INCONSISTENT_CLUSTER_ID(104, "The clusterId in the request does not match that found on the server.", InconsistentClusterIdException::new), TRANSACTIONAL_ID_NOT_FOUND(105, "The transactionalId could not be found.", TransactionalIdNotFoundException::new), FETCH_SESSION_TOPIC_ID_ERROR(106, "The fetch session encountered inconsistent topic ID usage.", FetchSessionTopicIdException::new), INELIGIBLE_REPLICA(107, "The new ISR contains at least one ineligible replica.", IneligibleReplicaException::new), NEW_LEADER_ELECTED(108, "The AlterPartition request successfully updated the partition state but the leader has changed.", NewLeaderElectedException::new), OFFSET_MOVED_TO_TIERED_STORAGE(109, "The requested offset is moved to tiered storage.", OffsetMovedToTieredStorageException::new), FENCED_MEMBER_EPOCH(110, "The member epoch is fenced by the group coordinator. The member must abandon all its partitions and rejoin.", FencedMemberEpochException::new), UNRELEASED_INSTANCE_ID(111, "The instance ID is still used by another member in the consumer group. That member must leave first.", UnreleasedInstanceIdException::new), UNSUPPORTED_ASSIGNOR(112, "The assignor or its version range is not supported by the consumer group.", UnsupportedAssignorException::new), STALE_MEMBER_EPOCH(113, "The member epoch is stale. The member must retry after receiving its updated member epoch via the ConsumerGroupHeartbeat API.", StaleMemberEpochException::new), MISMATCHED_ENDPOINT_TYPE(114, "The request was sent to an endpoint of the wrong type.", MismatchedEndpointTypeException::new), UNSUPPORTED_ENDPOINT_TYPE(115, "This endpoint type is not supported yet.", UnsupportedEndpointTypeException::new), UNKNOWN_CONTROLLER_ID(116, "This controller ID is not known.", UnknownControllerIdException::new), UNKNOWN_SUBSCRIPTION_ID(117, "Client sent a push telemetry request with an invalid or outdated subscription ID.", UnknownSubscriptionIdException::new), TELEMETRY_TOO_LARGE(118, "Client sent a push telemetry request larger than the maximum size the broker will accept.", TelemetryTooLargeException::new), INVALID_REGISTRATION(119, "The controller has considered the broker registration to be invalid.", InvalidRegistrationException::new), TRANSACTION_ABORTABLE(120, "The server encountered an error with the transaction. The client can abort the transaction to continue using this transactional ID.", TransactionAbortableException::new), INVALID_RECORD_STATE(121, "The record state is invalid. The acknowledgement of delivery could not be completed.", InvalidRecordStateException::new), SHARE_SESSION_NOT_FOUND(122, "The share session was not found.", ShareSessionNotFoundException::new), INVALID_SHARE_SESSION_EPOCH(123, "The share session epoch is invalid.", InvalidShareSessionEpochException::new), FENCED_STATE_EPOCH(124, "The share coordinator rejected the request because the share-group state epoch did not match.", FencedStateEpochException::new), INVALID_VOTER_KEY(125, "The voter key doesn't match the receiving replica's key.", InvalidVoterKeyException::new), DUPLICATE_VOTER(126, "The voter is already part of the set of voters.", DuplicateVoterException::new), VOTER_NOT_FOUND(127, "The voter is not part of the set of voters.", VoterNotFoundException::new), INVALID_REGULAR_EXPRESSION(128, "The regular expression is not valid.", InvalidRegularExpression::new), REBOOTSTRAP_REQUIRED(129, "Client metadata is stale. The client should rebootstrap to obtain new metadata.", RebootstrapRequiredException::new), STREAMS_INVALID_TOPOLOGY(130, "The supplied topology is invalid.", StreamsInvalidTopologyException::new), STREAMS_INVALID_TOPOLOGY_EPOCH(131, "The supplied topology epoch is invalid.", StreamsInvalidTopologyEpochException::new), STREAMS_TOPOLOGY_FENCED(132, "The supplied topology epoch is outdated.", StreamsTopologyFencedException::new), SHARE_SESSION_LIMIT_REACHED(133, "The limit of share sessions has been reached.", ShareSessionLimitReachedException::new); private static final Logger log = LoggerFactory.getLogger(Errors.class); private static final Map<Class<?>, Errors> CLASS_TO_ERROR = new HashMap<>(); private static final Map<Short, Errors> CODE_TO_ERROR = new HashMap<>(); static { for (Errors error : Errors.values()) { if (CODE_TO_ERROR.put(error.code(), error) != null) throw new ExceptionInInitializerError("Code " + error.code() + " for error " + error + " has already been used"); if (error.exception != null) CLASS_TO_ERROR.put(error.exception.getClass(), error); } } private final short code; private final Function<String, ApiException> builder; private final ApiException exception; Errors(int code, String defaultExceptionString, Function<String, ApiException> builder) { this.code = (short) code; this.builder = builder; this.exception = builder.apply(defaultExceptionString); } /** * An instance of the exception */ public ApiException exception() { return this.exception; } /** * Create an instance of the ApiException that contains the given error message. * * @param message The message string to set. * @return The exception. */ public ApiException exception(String message) { if (message == null) { // If no error message was specified, return an exception with the default error message. return exception; } // Return an exception with the given error message. return builder.apply(message); } /** * Returns the class name of the exception or null if this is {@code Errors.NONE}. */ public String exceptionName() { return exception == null ? null : exception.getClass().getName(); } /** * The error code for the exception */ public short code() { return this.code; } /** * Throw the exception corresponding to this error if there is one */ public void maybeThrow() { if (exception != null) { throw this.exception; } } /** * Get a friendly description of the error (if one is available). * @return the error message */ public String message() { if (exception != null) return exception.getMessage(); return toString(); } /** * Throw the exception if there is one */ public static Errors forCode(short code) { Errors error = CODE_TO_ERROR.get(code); if (error != null) { return error; } else { log.warn("Unexpected error code: {}.", code); return UNKNOWN_SERVER_ERROR; } } /** * Return the error instance associated with this exception or any of its superclasses (or UNKNOWN if there is none). * If there are multiple matches in the class hierarchy, the first match starting from the bottom is used. */ public static Errors forException(Throwable t) { Throwable cause = maybeUnwrapException(t); Class<?> clazz = cause.getClass(); while (clazz != null) { Errors error = CLASS_TO_ERROR.get(clazz); if (error != null) return error; clazz = clazz.getSuperclass(); } return UNKNOWN_SERVER_ERROR; } /** * Check if a Throwable is a commonly wrapped exception type (e.g. `CompletionException`) and return * the cause if so. This is useful to handle cases where exceptions may be raised from a future or a * completion stage (as might be the case for requests sent to the controller in `ControllerApis`). * * @param t The Throwable to check * @return The throwable itself or its cause if it is an instance of a commonly wrapped exception type */ public static Throwable maybeUnwrapException(Throwable t) { if (t instanceof CompletionException || t instanceof ExecutionException) { return t.getCause(); } else { return t; } } private static String toHtml() { final StringBuilder b = new StringBuilder(); b.append("<table class=\"data-table\"><tbody>\n"); b.append("<tr>"); b.append("<th>Error</th>\n"); b.append("<th>Code</th>\n"); b.append("<th>Retriable</th>\n"); b.append("<th>Description</th>\n"); b.append("</tr>\n"); for (Errors error : Errors.values()) { b.append("<tr>"); b.append("<td>"); b.append(error.name()); b.append("</td>"); b.append("<td>"); b.append(error.code()); b.append("</td>"); b.append("<td>"); b.append(error.exception() != null && error.exception() instanceof RetriableException ? "True" : "False"); b.append("</td>"); b.append("<td>"); b.append(error.exception() != null ? error.exception().getMessage() : ""); b.append("</td>"); b.append("</tr>\n"); } b.append("</tbody></table>\n"); return b.toString(); } public static void main(String[] args) { System.out.println(toHtml()); } }
apache/openjpa
36,483
openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/kernel/TableJDBCSeq.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.openjpa.jdbc.kernel; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.concurrent.ConcurrentHashMap; import jakarta.transaction.NotSupportedException; import org.apache.openjpa.conf.OpenJPAConfiguration; import org.apache.openjpa.jdbc.conf.JDBCConfiguration; import org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl; import org.apache.openjpa.jdbc.identifier.DBIdentifier; import org.apache.openjpa.jdbc.identifier.DBIdentifier.DBIdentifierType; import org.apache.openjpa.jdbc.identifier.Normalizer; import org.apache.openjpa.jdbc.identifier.QualifiedDBIdentifier; import org.apache.openjpa.jdbc.meta.ClassMapping; import org.apache.openjpa.jdbc.schema.Column; import org.apache.openjpa.jdbc.schema.PrimaryKey; import org.apache.openjpa.jdbc.schema.Schema; import org.apache.openjpa.jdbc.schema.SchemaGroup; import org.apache.openjpa.jdbc.schema.SchemaTool; import org.apache.openjpa.jdbc.schema.Schemas; import org.apache.openjpa.jdbc.schema.Table; import org.apache.openjpa.jdbc.schema.Unique; import org.apache.openjpa.jdbc.sql.DBDictionary; import org.apache.openjpa.jdbc.sql.Row; import org.apache.openjpa.jdbc.sql.SQLBuffer; import org.apache.openjpa.lib.conf.Configurable; import org.apache.openjpa.lib.conf.Configuration; import org.apache.openjpa.lib.conf.Configurations; import org.apache.openjpa.lib.identifier.IdentifierUtil; import org.apache.openjpa.lib.log.Log; import org.apache.openjpa.lib.util.Localizer; import org.apache.openjpa.lib.util.Options; import org.apache.openjpa.lib.util.StringUtil; import org.apache.openjpa.meta.JavaTypes; import org.apache.openjpa.util.InvalidStateException; import org.apache.openjpa.util.UserException; //////////////////////////////////////////////////////////// // NOTE: Do not change property names; see SequenceMetaData // and SequenceMapping for standard property names. //////////////////////////////////////////////////////////// /** * {@link JDBCSeq} implementation that uses a database table * for sequence number generation. This base implementation uses a single * row for a global sequence number. * * @author Abe White */ public class TableJDBCSeq extends AbstractJDBCSeq implements Configurable { public static final String ACTION_DROP = "drop"; public static final String ACTION_ADD = "add"; public static final String ACTION_GET = "get"; public static final String ACTION_SET = "set"; public static final String DEFAULT_TABLE = "OPENJPA_SEQUENCE_TABLE"; private static final Localizer _loc = Localizer.forPackage (TableJDBCSeq.class); private transient JDBCConfiguration _conf = null; private transient Log _log = null; private int _alloc = 50; private int _intValue = 1; private final ConcurrentHashMap<ClassMapping, Status> _stat = new ConcurrentHashMap<>(); private DBIdentifier _table = DBIdentifier.newTable(DEFAULT_TABLE); private DBIdentifier _seqColumnName = DBIdentifier.newColumn("SEQUENCE_VALUE"); private DBIdentifier _pkColumnName = DBIdentifier.newColumn("ID"); private DBIdentifier[] _uniqueColumnNames; private DBIdentifier _uniqueConstraintName = DBIdentifier.NULL; private Column _seqColumn = null; private Column _pkColumn = null; /** * The sequence table name. Defaults to <code>OPENJPA_SEQUENCE_TABLE</code>. * By default, the table will be placed in the first schema listed in your * <code>openjpa.jdbc.Schemas</code> property, or in the default schema if * the property is not given. If you specify a table name in the form * <code>&lt;schema&gt;.&lt;table&gt;</code>, then the given schema * will be used. */ public String getTable() { return _table.getName(); } /** * The sequence table name. Defaults to <code>OPENJPA_SEQUENCE_TABLE</code>. * By default, the table will be placed in the first schema listed in your * <code>openjpa.jdbc.Schemas</code> property, or in the default schema if * the property is not given. If you specify a table name in the form * <code>&lt;schema&gt;.&lt;table&gt;</code>, then the given schema * will be used. */ public void setTable(String name) { // Split the name into its individual parts String[] names = Normalizer.splitName(name); // Join the name back together. This will delimit as appropriate. _table = DBIdentifier.newTable(Normalizer.joinNames(names)); } /** * @deprecated Use {@link #setTable}. Retained for * backwards-compatibility with auto-configuration. */ @Deprecated public void setTableName(String name) { setTable(name); } /** * The name of the column that holds the sequence value. Defaults * to <code>SEQUENCE_VALUE</code>. */ public String getSequenceColumn() { return _seqColumnName.getName(); } /** * The name of the column that holds the sequence value. Defaults * to <code>SEQUENCE_VALUE</code>. */ public void setSequenceColumn(String sequenceColumn) { _seqColumnName = DBIdentifier.newColumn(sequenceColumn); } /** * The name of the table's primary key column. Defaults to * <code>ID</code>. */ public String getPrimaryKeyColumn() { return _pkColumnName.getName(); } public DBIdentifier getPrimaryKeyColumnIdentifier() { return _pkColumnName; } /** * The name of the table's primary key column. Defaults to * <code>ID</code>. */ public void setPrimaryKeyColumn(String primaryKeyColumn) { _pkColumnName = DBIdentifier.newColumn(primaryKeyColumn, _conf.getDBDictionaryInstance().delimitAll()); } /** * Return the number of sequences to allocate for each update of the * sequence table. Sequence numbers will be grabbed in blocks of this * value to reduce the number of transactions that must be performed on * the sequence table. */ public int getAllocate() { return _alloc; } /** * Return the number of sequences to allocate for each update of the * sequence table. Sequence numbers will be grabbed in blocks of this * value to reduce the number of transactions that must be performed on * the sequence table. */ public void setAllocate(int alloc) { _alloc = alloc; } /** * Return the number as the initial number for the * GeneratedValue.TABLE strategy to start with. * @return an initial number */ public int getInitialValue() { return _intValue; } /** * Set the initial number in the table for the GeneratedValue.TABLE * strategy to use as initial number. * @param intValue. The initial number */ public void setInitialValue(int intValue) { _intValue = intValue; } /** * Sets the names of the columns on which a unique constraint is set. * @param columnsNames are passed as a single String concatenated with * a '|' character. This method parses it back to array of Strings. */ public void setUniqueColumns(String columnNames) { _uniqueColumnNames = (StringUtil.isEmpty(columnNames)) ? null : DBIdentifier.split(columnNames, DBIdentifierType.COLUMN, IdentifierUtil.BAR); } public String getUniqueColumns() { return Normalizer.joinNames(DBIdentifier.toStringArray(_uniqueColumnNames), IdentifierUtil.BAR); } /** * @deprecated Use {@link #setAllocate}. Retained for backwards * compatibility of auto-configuration. */ @Deprecated public void setIncrement(int inc) { setAllocate(inc); } @Override public JDBCConfiguration getConfiguration() { return _conf; } @Override public void setConfiguration(Configuration conf) { _conf = (JDBCConfiguration) conf; _log = _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); } @Override public void startConfiguration() { } @Override public void endConfiguration() { buildTable(); } @Override public void addSchema(ClassMapping mapping, SchemaGroup group) { // Since the table is created by openjpa internally // we can create the table for each schema within the PU // in here. Schema[] schemas = group.getSchemas(); for (Schema value : schemas) { QualifiedDBIdentifier path = QualifiedDBIdentifier.getPath(_table); DBIdentifier schemaName = path.getSchemaName(); if (DBIdentifier.isEmpty(schemaName)) { schemaName = Schemas.getNewTableSchemaIdentifier(_conf); } if (DBIdentifier.isNull(schemaName)) { schemaName = value.getIdentifier(); } // create table in this group Schema schema = group.getSchema(schemaName); if (schema == null) { schema = group.addSchema(schemaName); } Table copy = schema.importTable(_pkColumn.getTable()); // importTable() does not import unique constraints Unique[] uniques = _pkColumn.getTable().getUniques(); for (Unique u : uniques) { copy.importUnique(u); } // we need to reset the table name in the column with the // fully qualified name for matching the table name from the // Column. _pkColumn.resetTableIdentifier(QualifiedDBIdentifier.newPath(schemaName, _pkColumn.getTableIdentifier())); // some databases require to create an index for the sequence table _conf.getDBDictionaryInstance().createIndexIfNecessary(schema, _table, _pkColumn); } } @Override protected Object nextInternal(JDBCStore store, ClassMapping mapping) throws Exception { // if needed, grab the next handful of ids Status stat = getStatus(mapping); if (stat == null) throw new InvalidStateException(_loc.get("bad-seq-type", getClass(), mapping)); while (true) { synchronized (stat) { // make sure seq is at least 1, since autoassigned ids of 0 can // conflict with uninitialized values stat.seq = Math.max(stat.seq, 1); if (stat.seq < stat.max) return stat.seq++; allocateSequence(store, mapping, stat, _alloc, true); } } } @Override protected Object currentInternal(JDBCStore store, ClassMapping mapping) throws Exception { if (current == null) { CurrentSequenceRunnable runnable = new CurrentSequenceRunnable(store, mapping); try { if (suspendInJTA()) { // NotSupportedException is wrapped in a StoreException by // the caller. _conf.getManagedRuntimeInstance().doNonTransactionalWork( runnable); } else { runnable.run(); } } catch (RuntimeException re) { throw (Exception) (re.getCause() == null ? re : re.getCause()); } } return super.currentInternal(store, mapping); } @Override protected void allocateInternal(int count, JDBCStore store, ClassMapping mapping) throws SQLException { Status stat = getStatus(mapping); if (stat == null) return; while (true) { int available; synchronized (stat) { available = (int) (stat.max - stat.seq); if (available >= count) return; } allocateSequence(store, mapping, stat, count - available, false); } } /** * Return the appropriate status object for the given class, or null * if cannot handle the given class. The mapping may be null. */ protected Status getStatus(ClassMapping mapping) { Status status = _stat.get(mapping); if (status == null){ status = new Status(); Status tStatus = _stat.putIfAbsent(mapping, status); // This can happen if another thread calls .put(..) sometime after our call to get. Return // the value from the putIfAbsent call as that is truly in the map. if (tStatus != null) { return tStatus; } } return status; } /** * Add the primary key column to the given table and return it. */ protected Column addPrimaryKeyColumn(Table table) { DBDictionary dict = _conf.getDBDictionaryInstance(); Column pkColumn = table.addColumn(dict.getValidColumnName(getPrimaryKeyColumnIdentifier(), table)); pkColumn.setType(dict.getPreferredType(Types.TINYINT)); pkColumn.setJavaType(JavaTypes.INT); return pkColumn; } /** * Return the primary key value for the sequence table for the given class. */ protected Object getPrimaryKey(ClassMapping mapping) { return 0; } /** * Creates the object-level representation of the sequence table. */ private void buildTable() { DBIdentifier tableName = DBIdentifier.NULL; DBIdentifier schemaName = DBIdentifier.NULL; QualifiedDBIdentifier path = QualifiedDBIdentifier.getPath(_table); if (!DBIdentifier.isEmpty(path.getSchemaName())) { schemaName = path.getSchemaName(); tableName = path.getUnqualifiedName(); } else { tableName = _table; } if (DBIdentifier.isEmpty(schemaName)) { schemaName = Schemas.getNewTableSchemaIdentifier(_conf); } SchemaGroup group = new SchemaGroup(); Schema schema = group.addSchema(schemaName); Table table = schema.addTable(tableName); _pkColumn = addPrimaryKeyColumn(table); PrimaryKey pk = table.addPrimaryKey(); pk.addColumn(_pkColumn); DBDictionary dict = _conf.getDBDictionaryInstance(); DBIdentifier _delimitedSeqColumnName = dict.delimitAll() ? DBIdentifier.newColumn(this._seqColumnName.getName(), true) : this._seqColumnName; _seqColumn = table.addColumn(dict.getValidColumnName (_delimitedSeqColumnName, table)); _seqColumn.setType(dict.getPreferredType(Types.BIGINT)); _seqColumn.setJavaType(JavaTypes.LONG); if (_uniqueColumnNames != null) { DBIdentifier uniqueName = _uniqueConstraintName; if (DBIdentifier.isEmpty(uniqueName)) { uniqueName = dict.getValidUniqueName(DBIdentifier.newConstraint("UNQ"), table); } Unique u = table.addUnique(uniqueName); for (DBIdentifier columnName : _uniqueColumnNames) { if (!table.containsColumn(columnName, _conf.getDBDictionaryInstance())) throw new UserException(_loc.get("unique-missing-column", columnName, table.getIdentifier(), table.getColumnNames())); Column col = table.getColumn(columnName); u.addColumn(col); } } } /** * Updates the max available sequence value. */ private void allocateSequence(JDBCStore store, ClassMapping mapping, Status stat, int alloc, boolean updateStatSeq) throws SQLException { Runnable runnable = new AllocateSequenceRunnable( store, mapping, stat, alloc, updateStatSeq); try { if (suspendInJTA()) { // NotSupportedException is wrapped in a StoreException by // the caller. try { _conf.getManagedRuntimeInstance().doNonTransactionalWork( runnable); } catch(NotSupportedException nse) { SQLException sqlEx = new SQLException( nse.getLocalizedMessage(), nse); throw sqlEx; } } else { runnable.run(); } } catch (RuntimeException re) { Throwable e = re.getCause(); if(e instanceof SQLException ) throw (SQLException) e; else throw re; } } /** * Inserts the initial sequence column into the database. * * @param mapping * ClassMapping for the class whose sequence column will be * updated * @param conn * Connection used issue SQL statements. */ private void insertSequence(ClassMapping mapping, Connection conn) throws SQLException { if (_log.isTraceEnabled()) _log.trace(_loc.get("insert-seq")); Object pk = getPrimaryKey(mapping); if (pk == null) throw new InvalidStateException(_loc.get("bad-seq-type", getClass(), mapping)); DBDictionary dict = _conf.getDBDictionaryInstance(); DBIdentifier tableName = resolveTableIdentifier(mapping, _pkColumn.getTable()); SQLBuffer insert = new SQLBuffer(dict).append("INSERT INTO "). append(tableName).append(" ("). append(_pkColumn).append(", ").append(_seqColumn). append(") VALUES ("). appendValue(pk, _pkColumn).append(", "). appendValue(_intValue, _seqColumn).append(")"); boolean wasAuto = conn.getAutoCommit(); if (!wasAuto && !suspendInJTA()) conn.setAutoCommit(true); PreparedStatement stmnt = null; try { stmnt = prepareStatement(conn, insert); dict.setTimeouts(stmnt, _conf, true); executeUpdate(_conf, conn, stmnt, insert, Row.ACTION_INSERT); } finally { if (stmnt != null) try { stmnt.close(); } catch (SQLException se) {} if (!wasAuto && !suspendInJTA()) conn.setAutoCommit(false); } } /** * Get the current sequence value. * * @param mapping * ClassMapping of the entity whose sequence value will be * obtained. * @param conn * Connection used issue SQL statements. * * @return The current sequence value, or <code>SEQUENCE_NOT_FOUND</code> * if the sequence could not be found. */ protected long getSequence(ClassMapping mapping, Connection conn) throws SQLException { if (_log.isTraceEnabled()) _log.trace(_loc.get("get-seq")); Object pk = getPrimaryKey(mapping); if (pk == null) return -1; DBDictionary dict = _conf.getDBDictionaryInstance(); SQLBuffer sel = new SQLBuffer(dict).append(_seqColumn); SQLBuffer where = new SQLBuffer(dict).append(_pkColumn).append(" = "). appendValue(pk, _pkColumn); DBIdentifier tableName = resolveTableIdentifier(mapping, _seqColumn.getTable()); SQLBuffer tables = new SQLBuffer(dict).append(tableName); SQLBuffer select = dict.toSelect(sel, null, tables, where, null, null, null, false, dict.supportsSelectForUpdate, 0, Long.MAX_VALUE, false, true); PreparedStatement stmnt = null; ResultSet rs = null; try { stmnt = prepareStatement(conn, select); dict.setTimeouts(stmnt, _conf, false); rs = executeQuery(_conf, conn, stmnt, select); return getSequence(rs, dict); } finally { if (rs != null) try { rs.close(); } catch (SQLException se) {} if (stmnt != null) try { stmnt.close(); } catch (SQLException se) {} } } /** * Grabs the next handful of sequence numbers. * * @return true if the sequence was updated, false if no sequence * row existed for this mapping */ protected boolean setSequence(ClassMapping mapping, Status stat, int inc, boolean updateStatSeq, Connection conn) throws SQLException { if (_log.isTraceEnabled()) _log.trace(_loc.get("update-seq")); Object pk = getPrimaryKey(mapping); if (pk == null) throw new InvalidStateException(_loc.get("bad-seq-type", getClass(), mapping)); DBDictionary dict = _conf.getDBDictionaryInstance(); SQLBuffer where = new SQLBuffer(dict).append(_pkColumn).append(" = "). appendValue(pk, _pkColumn); // loop until we have a successful atomic select/update sequence long cur = 0; PreparedStatement stmnt; ResultSet rs; SQLBuffer upd; for (int updates = 0; updates == 0;) { stmnt = null; rs = null; try { cur = getSequence(mapping, conn); if (cur == -1) return false; // update the value upd = new SQLBuffer(dict); DBIdentifier tableName = resolveTableIdentifier(mapping, _seqColumn.getTable()); upd.append("UPDATE ").append(tableName). append(" SET ").append(_seqColumn).append(" = "). appendValue(cur + inc, _seqColumn). append(" WHERE ").append(where).append(" AND "). append(_seqColumn).append(" = "). appendValue(cur, _seqColumn); stmnt = prepareStatement(conn, upd); dict.setTimeouts(stmnt, _conf, true); updates = executeUpdate(_conf, conn, stmnt, upd, Row.ACTION_UPDATE); } finally { if (rs != null) try { rs.close(); } catch (SQLException se) {} if (stmnt != null) try { stmnt.close(); } catch (SQLException se) {} } } // setup new sequence range synchronized (stat) { if (updateStatSeq && stat.seq < cur) stat.seq = cur; if (stat.max < cur + inc) stat.max = cur + inc; } return true; } /** * Resolve a fully qualified table name * * @param class * mapping to get the schema name * @deprecated */ @Deprecated public String resolveTableName(ClassMapping mapping, Table table) { return resolveTableIdentifier(mapping, table).getName(); } /** * Resolve a fully qualified table name * * @param class * mapping to get the schema name */ public DBIdentifier resolveTableIdentifier(ClassMapping mapping, Table table) { DBIdentifier sName = mapping.getTable().getSchemaIdentifier(); DBIdentifier tableName = DBIdentifier.NULL; //OPENJPA-2650: Don't use a schema name if the user has requested, //via useSchemaName, to not use one. if (!_conf.getDBDictionaryInstance().useSchemaName){ tableName = table.getIdentifier(); } else if (DBIdentifier.isNull(sName)) { tableName = table.getFullIdentifier(); } else if (!DBIdentifier.isNull(table.getSchemaIdentifier())) { tableName = table.getFullIdentifier(); } else { tableName = QualifiedDBIdentifier.newPath(sName, table.getIdentifier()); } return tableName; } /** * Creates the sequence table in the DB. */ public void refreshTable() throws SQLException { if (_log.isInfoEnabled()) _log.info(_loc.get("make-seq-table")); // create the table SchemaTool tool = new SchemaTool(_conf); tool.setIgnoreErrors(true); tool.createTable(_pkColumn.getTable()); } /** * Drops the sequence table in the DB. */ public void dropTable() throws SQLException { if (_log.isInfoEnabled()) _log.info(_loc.get("drop-seq-table")); // drop the table SchemaTool tool = new SchemaTool(_conf); tool.setIgnoreErrors(true); tool.dropTable(_pkColumn.getTable()); } ///////// // Main ///////// /** * Usage: java org.apache.openjpa.jdbc.schema.TableJDBCSequence [option]* * -action/-a &lt;add | drop | get | set&gt; [value] * Where the following options are recognized. * <ul> * <li><i>-properties/-p &lt;properties file or resource&gt;</i>: The * path or resource name of a OpenJPA properties file containing * information such as the license key and connection data as * outlined in {@link JDBCConfiguration}. Optional.</li> * <li><i>-&lt;property name&gt; &lt;property value&gt;</i>: All bean * properties of the OpenJPA {@link JDBCConfiguration} can be set by * using their names and supplying a value. For example: * <code>-licenseKey adslfja83r3lkadf</code></li> * </ul> * The various actions are as follows. * <ul> * <li><i>add</i>: Create the sequence table.</li> * <li><i>drop</i>: Drop the sequence table.</li> * <li><i>get</i>: Print the current sequence value.</li> * <li><i>set</i>: Set the sequence value.</li> * </ul> */ public static void main(String[] args) throws Exception { Options opts = new Options(); final String[] arguments = opts.setFromCmdLine(args); boolean ret = Configurations.runAgainstAllAnchors(opts, new Configurations.Runnable() { @Override public boolean run(Options opts) throws Exception { JDBCConfiguration conf = new JDBCConfigurationImpl(); try { return TableJDBCSeq.run(conf, arguments, opts); } finally { conf.close(); } } }); if (!ret) { // START - ALLOW PRINT STATEMENTS System.out.println(_loc.get("seq-usage")); // STOP - ALLOW PRINT STATEMENTS } } /** * Run the tool. Returns false if invalid options were given. */ public static boolean run(JDBCConfiguration conf, String[] args, Options opts) throws Exception { String action = opts.removeProperty("action", "a", null); Configurations.populateConfiguration(conf, opts); return run(conf, args, action); } /** * Run the tool. Return false if an invalid option was given. */ public static boolean run(JDBCConfiguration conf, String[] args, String action) throws Exception { if (args.length > 1 || (args.length != 0 && !ACTION_SET.equals(action))) return false; TableJDBCSeq seq = new TableJDBCSeq(); String props = Configurations.getProperties(conf.getSequence()); Configurations.configureInstance(seq, conf, props); if (ACTION_DROP.equals(action)) seq.dropTable(); else if (ACTION_ADD.equals(action)) seq.refreshTable(); else if (ACTION_GET.equals(action) || ACTION_SET.equals(action)) { Connection conn = conf.getDataSource2(null).getConnection(); try { long cur = seq.getSequence(null, conn); if (ACTION_GET.equals(action)) { // START - ALLOW PRINT STATEMENTS System.out.println(cur); // STOP - ALLOW PRINT STATEMENTS } else { long set; if (args.length > 0) set = Long.parseLong(args[0]); else set = cur + seq.getAllocate(); if (set < cur) set = cur; else { Status stat = seq.getStatus(null); seq.setSequence(null, stat, (int) (set - cur), true, conn); set = stat.seq; } // START - ALLOW PRINT STATEMENTS System.err.println(set); // STOP - ALLOW PRINT STATEMENTS } } catch (NumberFormatException nfe) { return false; } finally { try { conn.close(); } catch (SQLException se) {} } } else return false; return true; } /** * Helper struct to hold status information. */ protected static class Status implements Serializable { private static final long serialVersionUID = 1L; public long seq = 1L; public long max = 0L; } /** * This method is to provide override for non-JDBC or JDBC-like * implementation of preparing statement. */ protected PreparedStatement prepareStatement(Connection conn, SQLBuffer buf) throws SQLException { return buf.prepareStatement(conn); } /** * This method is to provide override for non-JDBC or JDBC-like * implementation of executing update. */ protected int executeUpdate(JDBCConfiguration conf, Connection conn, PreparedStatement stmnt, SQLBuffer buf, int opcode) throws SQLException { return stmnt.executeUpdate(); } /** * This method is to provide override for non-JDBC or JDBC-like * implementation of executing query. */ protected ResultSet executeQuery(JDBCConfiguration conf, Connection conn, PreparedStatement stmnt, SQLBuffer buf) throws SQLException { return stmnt.executeQuery(); } /** * This method is to provide override for non-JDBC or JDBC-like * implementation of getting sequence from the result set. */ protected long getSequence(ResultSet rs, DBDictionary dict) throws SQLException { if (rs == null || !rs.next()) return -1; return dict.getLong(rs, 1); } public void setUniqueConstraintName(String uniqueConstraintName) { _uniqueConstraintName = DBIdentifier.newConstraint(uniqueConstraintName); } public void setUniqueConstraintName(DBIdentifier uniqueConstraintName) { _uniqueConstraintName = uniqueConstraintName; } public String getUniqueConstraintName() { return _uniqueConstraintName.getName(); } public DBIdentifier getUniqueConstraintIdentifier() { return _uniqueConstraintName; } /** * AllocateSequenceRunnable is a runnable wrapper that will inserts the * initial sequence value into the database. */ protected class AllocateSequenceRunnable implements Runnable { JDBCStore store = null; ClassMapping mapping = null; Status stat = null; int alloc; boolean updateStatSeq; AllocateSequenceRunnable(JDBCStore store, ClassMapping mapping, Status stat, int alloc, boolean updateStatSeq) { this.store = store; this.mapping = mapping; this.stat = stat; this.alloc = alloc; this.updateStatSeq = updateStatSeq; } /** * This method actually obtains the current sequence value. * * @throws RuntimeException * any SQLExceptions that occur when obtaining the sequence * value are wrapped in a runtime exception to avoid * breaking the Runnable method signature. The caller can * obtain the "real" exception by calling getCause(). */ @Override public void run() throws RuntimeException { Connection conn = null; SQLException err = null; try { // Try to use the store's connection. conn = getConnection(store); boolean sequenceSet = setSequence(mapping, stat, alloc, updateStatSeq, conn); closeConnection(conn); if (!sequenceSet) { // insert a new sequence column. Prefer connection2 / non-jta-data-source when inserting a // sequence column regardless of Seq.type. conn = _conf.getDataSource2(store.getContext()).getConnection(); try { insertSequence(mapping, conn); } catch (SQLException e) { // it is possible another thread already got in and inserted this sequence. Try to keep going if (_log.isTraceEnabled()) { _log.trace( "Caught an exception while trying to insert sequence. Will try to reselect the " + "seqence. ", e); } } conn.close(); // now we should be able to update using the connection per // on the seq type. conn = getConnection(store); if (!setSequence(mapping, stat, alloc, updateStatSeq, conn)) { throw (err != null) ? err : new SQLException(_loc.get( "no-seq-row", mapping, _table).getMessage()); } closeConnection(conn); } } catch (SQLException e) { if (conn != null) { closeConnection(conn); } RuntimeException re = new RuntimeException(e.getMessage(), e); throw re; } } } /** * CurentSequenceRunnable is a runnable wrapper which obtains the current * sequence value from the database. */ protected class CurrentSequenceRunnable implements Runnable { private JDBCStore _store; private ClassMapping _mapping; CurrentSequenceRunnable(JDBCStore store, ClassMapping mapping) { _store = store; _mapping = mapping; } /** * This method actually obtains the current sequence value. * * @throws RuntimeException * any SQLExceptions that occur when obtaining the sequence * value are wrapped in a runtime exception to avoid * breaking the Runnable method signature. The caller can * obtain the "real" exception by calling getCause(). */ @Override public void run() throws RuntimeException { Connection conn = null; try { conn = getConnection(_store); long cur = getSequence(_mapping, conn); if (cur != -1 ) // USE the constant current = cur; } catch (SQLException sqle) { RuntimeException re = new RuntimeException(sqle.getMessage(), sqle); throw re; } finally { if (conn != null) { closeConnection(conn); } } } } }
googleapis/google-cloud-java
36,329
java-securitycenter/proto-google-cloud-securitycenter-v1beta1/src/main/java/com/google/cloud/securitycenter/v1beta1/SetFindingStateRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/securitycenter/v1beta1/securitycenter_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.securitycenter.v1beta1; /** * * * <pre> * Request message for updating a finding's state. * </pre> * * Protobuf type {@code google.cloud.securitycenter.v1beta1.SetFindingStateRequest} */ public final class SetFindingStateRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1beta1.SetFindingStateRequest) SetFindingStateRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SetFindingStateRequest.newBuilder() to construct. private SetFindingStateRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SetFindingStateRequest() { name_ = ""; state_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SetFindingStateRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycenter.v1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycenter.v1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest.class, com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. The relative resource name of the finding. See: * https://cloud.google.com/apis/design/resource_names#relative_resource_name * Example: * "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The relative resource name of the finding. See: * https://cloud.google.com/apis/design/resource_names#relative_resource_name * Example: * "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATE_FIELD_NUMBER = 2; private int state_ = 0; /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1beta1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for state. */ @java.lang.Override public int getStateValue() { return state_; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1beta1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The state. */ @java.lang.Override public com.google.cloud.securitycenter.v1beta1.Finding.State getState() { com.google.cloud.securitycenter.v1beta1.Finding.State result = com.google.cloud.securitycenter.v1beta1.Finding.State.forNumber(state_); return result == null ? com.google.cloud.securitycenter.v1beta1.Finding.State.UNRECOGNIZED : result; } public static final int START_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp startTime_; /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the startTime field is set. */ @java.lang.Override public boolean hasStartTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The startTime. */ @java.lang.Override public com.google.protobuf.Timestamp getStartTime() { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (state_ != com.google.cloud.securitycenter.v1beta1.Finding.State.STATE_UNSPECIFIED.getNumber()) { output.writeEnum(2, state_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getStartTime()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (state_ != com.google.cloud.securitycenter.v1beta1.Finding.State.STATE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, state_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getStartTime()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest)) { return super.equals(obj); } com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest other = (com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest) obj; if (!getName().equals(other.getName())) return false; if (state_ != other.state_) return false; if (hasStartTime() != other.hasStartTime()) return false; if (hasStartTime()) { if (!getStartTime().equals(other.getStartTime())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + STATE_FIELD_NUMBER; hash = (53 * hash) + state_; if (hasStartTime()) { hash = (37 * hash) + START_TIME_FIELD_NUMBER; hash = (53 * hash) + getStartTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for updating a finding's state. * </pre> * * Protobuf type {@code google.cloud.securitycenter.v1beta1.SetFindingStateRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1beta1.SetFindingStateRequest) com.google.cloud.securitycenter.v1beta1.SetFindingStateRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycenter.v1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycenter.v1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest.class, com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest.Builder.class); } // Construct using com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getStartTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; state_ = 0; startTime_ = null; if (startTimeBuilder_ != null) { startTimeBuilder_.dispose(); startTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.securitycenter.v1beta1.SecuritycenterService .internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_descriptor; } @java.lang.Override public com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest getDefaultInstanceForType() { return com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest build() { com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest buildPartial() { com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest result = new com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.state_ = state_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.startTime_ = startTimeBuilder_ == null ? startTime_ : startTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest) { return mergeFrom((com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest other) { if (other == com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.state_ != 0) { setStateValue(other.getStateValue()); } if (other.hasStartTime()) { mergeStartTime(other.getStartTime()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { state_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { input.readMessage(getStartTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. The relative resource name of the finding. See: * https://cloud.google.com/apis/design/resource_names#relative_resource_name * Example: * "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The relative resource name of the finding. See: * https://cloud.google.com/apis/design/resource_names#relative_resource_name * Example: * "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The relative resource name of the finding. See: * https://cloud.google.com/apis/design/resource_names#relative_resource_name * Example: * "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The relative resource name of the finding. See: * https://cloud.google.com/apis/design/resource_names#relative_resource_name * Example: * "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The relative resource name of the finding. See: * https://cloud.google.com/apis/design/resource_names#relative_resource_name * Example: * "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int state_ = 0; /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1beta1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for state. */ @java.lang.Override public int getStateValue() { return state_; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1beta1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The enum numeric value on the wire for state to set. * @return This builder for chaining. */ public Builder setStateValue(int value) { state_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1beta1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The state. */ @java.lang.Override public com.google.cloud.securitycenter.v1beta1.Finding.State getState() { com.google.cloud.securitycenter.v1beta1.Finding.State result = com.google.cloud.securitycenter.v1beta1.Finding.State.forNumber(state_); return result == null ? com.google.cloud.securitycenter.v1beta1.Finding.State.UNRECOGNIZED : result; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1beta1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The state to set. * @return This builder for chaining. */ public Builder setState(com.google.cloud.securitycenter.v1beta1.Finding.State value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; state_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Required. The desired State of the finding. * </pre> * * <code> * .google.cloud.securitycenter.v1beta1.Finding.State state = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearState() { bitField0_ = (bitField0_ & ~0x00000002); state_ = 0; onChanged(); return this; } private com.google.protobuf.Timestamp startTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> startTimeBuilder_; /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the startTime field is set. */ public boolean hasStartTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The startTime. */ public com.google.protobuf.Timestamp getStartTime() { if (startTimeBuilder_ == null) { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } else { return startTimeBuilder_.getMessage(); } } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } startTime_ = value; } else { startTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setStartTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (startTimeBuilder_ == null) { startTime_ = builderForValue.build(); } else { startTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && startTime_ != null && startTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getStartTimeBuilder().mergeFrom(value); } else { startTime_ = value; } } else { startTimeBuilder_.mergeFrom(value); } if (startTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearStartTime() { bitField0_ = (bitField0_ & ~0x00000004); startTime_ = null; if (startTimeBuilder_ != null) { startTimeBuilder_.dispose(); startTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getStartTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { if (startTimeBuilder_ != null) { return startTimeBuilder_.getMessageOrBuilder(); } else { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } } /** * * * <pre> * Required. The time at which the updated state takes effect. * </pre> * * <code>.google.protobuf.Timestamp start_time = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getStartTimeFieldBuilder() { if (startTimeBuilder_ == null) { startTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getStartTime(), getParentForChildren(), isClean()); startTime_ = null; } return startTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.securitycenter.v1beta1.SetFindingStateRequest) } // @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.SetFindingStateRequest) private static final com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest(); } public static com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SetFindingStateRequest> PARSER = new com.google.protobuf.AbstractParser<SetFindingStateRequest>() { @java.lang.Override public SetFindingStateRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SetFindingStateRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SetFindingStateRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/maven
36,601
impl/maven-testing/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.maven.api.plugin.testing; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.AccessibleObject; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.maven.api.MojoExecution; import org.apache.maven.api.Project; import org.apache.maven.api.Session; import org.apache.maven.api.di.Named; import org.apache.maven.api.di.Priority; import org.apache.maven.api.di.Provides; import org.apache.maven.api.di.Singleton; import org.apache.maven.api.di.testing.MavenDIExtension; import org.apache.maven.api.model.Build; import org.apache.maven.api.model.ConfigurationContainer; import org.apache.maven.api.model.Model; import org.apache.maven.api.model.Source; import org.apache.maven.api.plugin.Log; import org.apache.maven.api.plugin.Mojo; import org.apache.maven.api.plugin.descriptor.MojoDescriptor; import org.apache.maven.api.plugin.descriptor.Parameter; import org.apache.maven.api.plugin.descriptor.PluginDescriptor; import org.apache.maven.api.plugin.testing.stubs.MojoExecutionStub; import org.apache.maven.api.plugin.testing.stubs.PluginStub; import org.apache.maven.api.plugin.testing.stubs.ProducedArtifactStub; import org.apache.maven.api.plugin.testing.stubs.ProjectStub; import org.apache.maven.api.plugin.testing.stubs.RepositorySystemSupplier; import org.apache.maven.api.plugin.testing.stubs.SessionMock; import org.apache.maven.api.services.ArtifactDeployer; import org.apache.maven.api.services.ArtifactFactory; import org.apache.maven.api.services.ArtifactInstaller; import org.apache.maven.api.services.ArtifactManager; import org.apache.maven.api.services.LocalRepositoryManager; import org.apache.maven.api.services.ProjectBuilder; import org.apache.maven.api.services.ProjectManager; import org.apache.maven.api.services.RepositoryFactory; import org.apache.maven.api.services.VersionParser; import org.apache.maven.api.services.xml.ModelXmlFactory; import org.apache.maven.api.xml.XmlNode; import org.apache.maven.api.xml.XmlService; import org.apache.maven.configuration.internal.EnhancedComponentConfigurator; import org.apache.maven.di.Injector; import org.apache.maven.di.Key; import org.apache.maven.di.impl.DIException; import org.apache.maven.impl.InternalSession; import org.apache.maven.impl.model.DefaultModelPathTranslator; import org.apache.maven.impl.model.DefaultPathTranslator; import org.apache.maven.internal.impl.DefaultLog; import org.apache.maven.internal.xml.XmlPlexusConfiguration; import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; import org.apache.maven.model.v4.MavenMerger; import org.apache.maven.model.v4.MavenStaxReader; import org.apache.maven.plugin.PluginParameterExpressionEvaluatorV4; import org.apache.maven.plugin.descriptor.io.PluginDescriptorStaxReader; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; import org.codehaus.plexus.util.ReflectionUtils; import org.codehaus.plexus.util.xml.XmlStreamReader; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.eclipse.aether.RepositorySystem; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolutionException; import org.junit.jupiter.api.extension.ParameterResolver; import org.junit.platform.commons.support.AnnotationSupport; import org.slf4j.LoggerFactory; import static java.util.Objects.requireNonNull; /** * JUnit Jupiter extension that provides support for testing Maven plugins (Mojos). * This extension handles the lifecycle of Mojo instances in tests, including instantiation, * configuration, and dependency injection. * * <p>The extension is automatically registered when using the {@link MojoTest} annotation * on a test class. It provides the following features:</p> * <ul> * <li>Automatic Mojo instantiation based on {@link InjectMojo} annotations</li> * <li>Parameter injection using {@link MojoParameter} annotations</li> * <li>POM configuration handling</li> * <li>Project stub creation and configuration</li> * <li>Maven session and build context setup</li> * <li>Component dependency injection</li> * </ul> * * <p>Example usage in a test class:</p> * <pre> * {@code * @MojoTest * class MyMojoTest { * @Test * @InjectMojo(goal = "my-goal") * @MojoParameter(name = "outputDirectory", value = "${project.build.directory}/generated") * void testMojoExecution(MyMojo mojo) throws Exception { * mojo.execute(); * // verify execution results * } * } * } * </pre> * * <p>The extension supports two main injection scenarios:</p> * <ol> * <li>Method parameter injection: Mojo instances can be injected as test method parameters</li> * <li>Field injection: Components can be injected into test class fields using {@code @Inject}</li> * </ol> * * <p>For custom POM configurations, you can specify a POM file using the {@link InjectMojo#pom()} * attribute. The extension will merge this configuration with default test project settings.</p> * * <p>Base directory handling:</p> * <ul> * <li>Plugin basedir: The directory containing the plugin project</li> * <li>Test basedir: The directory containing test resources, configurable via {@link Basedir}</li> * </ul> * * @see MojoTest * @see InjectMojo * @see MojoParameter * @see Basedir * @since 4.0.0 */ public class MojoExtension extends MavenDIExtension implements ParameterResolver, BeforeEachCallback { /** The base directory of the plugin being tested */ protected static String pluginBasedir; /** The base directory for test resources */ protected static String basedir; /** * Gets the identifier for the current test method. * The format is "TestClassName-testMethodName". * * @return the test identifier */ public static String getTestId() { return context.getRequiredTestClass().getSimpleName() + "-" + context.getRequiredTestMethod().getName(); } /** * Gets the base directory for test resources. * If not explicitly set via {@link Basedir}, returns the plugin base directory. * * @return the base directory path * @throws NullPointerException if neither basedir nor plugin basedir is set */ public static String getBasedir() { return requireNonNull(basedir != null ? basedir : MavenDIExtension.basedir); } /** * Gets the base directory of the plugin being tested. * * @return the plugin base directory path * @throws NullPointerException if plugin basedir is not set */ public static String getPluginBasedir() { return requireNonNull(pluginBasedir); } /** * Determines if this extension can resolve the given parameter. * Returns true if the parameter is annotated with {@link InjectMojo} or * if its declaring method is annotated with {@link InjectMojo}. * * @param parameterContext the context for the parameter being resolved * @param extensionContext the current extension context * @return true if this extension can resolve the parameter */ @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return parameterContext.isAnnotated(InjectMojo.class) || parameterContext.getDeclaringExecutable().isAnnotationPresent(InjectMojo.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { try { Class<?> holder = parameterContext.getTarget().orElseThrow().getClass(); PluginDescriptor descriptor = extensionContext .getStore(ExtensionContext.Namespace.GLOBAL) .get(PluginDescriptor.class, PluginDescriptor.class); Model model = extensionContext.getStore(ExtensionContext.Namespace.GLOBAL).get(Model.class, Model.class); InjectMojo parameterInjectMojo = parameterContext.getAnnotatedElement().getAnnotation(InjectMojo.class); String goal; if (parameterInjectMojo != null) { String pom = parameterInjectMojo.pom(); if (pom != null && !pom.isEmpty()) { try (Reader r = openPomUrl(holder, pom, new Path[1])) { Model localModel = new MavenStaxReader().read(r); model = new MavenMerger().merge(localModel, model, false, null); model = new DefaultModelPathTranslator(new DefaultPathTranslator()) .alignToBaseDirectory(model, Paths.get(getBasedir()), null); } } goal = parameterInjectMojo.goal(); } else { InjectMojo methodInjectMojo = AnnotationSupport.findAnnotation( parameterContext.getDeclaringExecutable(), InjectMojo.class) .orElse(null); if (methodInjectMojo != null) { goal = methodInjectMojo.goal(); } else { goal = getGoalFromMojoImplementationClass( parameterContext.getParameter().getType()); } } Set<MojoParameter> mojoParameters = new LinkedHashSet<>(); for (AnnotatedElement ae : Arrays.asList(parameterContext.getDeclaringExecutable(), parameterContext.getAnnotatedElement())) { mojoParameters.addAll(AnnotationSupport.findRepeatableAnnotations(ae, MojoParameter.class)); } String[] coord = mojoCoordinates(goal); XmlNode pluginConfiguration = model.getBuild().getPlugins().stream() .filter(p -> Objects.equals(p.getGroupId(), coord[0]) && Objects.equals(p.getArtifactId(), coord[1])) .findFirst() .map(ConfigurationContainer::getConfiguration) .orElseGet(() -> XmlNode.newInstance("config")); List<XmlNode> children = mojoParameters.stream() .map(mp -> XmlNode.newInstance(mp.name(), mp.value())) .collect(Collectors.toList()); XmlNode config = XmlNode.newInstance("configuration", null, null, children, null); pluginConfiguration = XmlService.merge(config, pluginConfiguration); // load default config // pluginkey = groupId : artifactId : version : goal Mojo mojo = lookup(Mojo.class, coord[0] + ":" + coord[1] + ":" + coord[2] + ":" + coord[3]); for (MojoDescriptor mojoDescriptor : descriptor.getMojos()) { if (Objects.equals(mojoDescriptor.getGoal(), coord[3])) { if (pluginConfiguration != null) { pluginConfiguration = finalizeConfig(pluginConfiguration, mojoDescriptor); } } } Session session = getInjector().getInstance(Session.class); Project project = getInjector().getInstance(Project.class); MojoExecution mojoExecution = getInjector().getInstance(MojoExecution.class); ExpressionEvaluator evaluator = new WrapEvaluator( getInjector(), new PluginParameterExpressionEvaluatorV4(session, project, mojoExecution)); EnhancedComponentConfigurator configurator = new EnhancedComponentConfigurator(); configurator.configureComponent( mojo, new XmlPlexusConfiguration(pluginConfiguration), evaluator, null, null); return mojo; } catch (Exception e) { throw new ParameterResolutionException("Unable to resolve mojo", e); } } /** * The @Mojo annotation is only retained in the class file, not at runtime, * so we need to actually read the class file with ASM to find the annotation and * the goal. */ private static String getGoalFromMojoImplementationClass(Class<?> cl) throws IOException { return cl.getAnnotation(Named.class).value(); } @Override @SuppressWarnings("checkstyle:MethodLength") public void beforeEach(ExtensionContext context) throws Exception { if (pluginBasedir == null) { pluginBasedir = MavenDIExtension.getBasedir(); } basedir = AnnotationSupport.findAnnotation(context.getElement().orElseThrow(), Basedir.class) .map(Basedir::value) .orElse(pluginBasedir); if (basedir != null) { if (basedir.isEmpty()) { basedir = pluginBasedir + "/target/tests/" + context.getRequiredTestClass().getSimpleName() + "/" + context.getRequiredTestMethod().getName(); } else { basedir = basedir.replace("${basedir}", pluginBasedir); } } setContext(context); /* binder.install(ProviderMethodsModule.forObject(context.getRequiredTestInstance())); binder.requestInjection(context.getRequiredTestInstance()); binder.bind(Log.class).toInstance(new DefaultLog(LoggerFactory.getLogger("anonymous"))); binder.bind(ExtensionContext.class).toInstance(context); // Load maven 4 api Services interfaces and try to bind them to the (possible) mock instances // returned by the (possibly) mock InternalSession try { for (ClassPath.ClassInfo clazz : ClassPath.from(getClassLoader()).getAllClasses()) { if ("org.apache.maven.api.services".equals(clazz.getPackageName())) { Class<?> load = clazz.load(); if (Service.class.isAssignableFrom(load)) { Class<Service> svc = (Class) load; binder.bind(svc).toProvider(() -> { try { return getContainer() .lookup(InternalSession.class) .getService(svc); } catch (ComponentLookupException e) { throw new RuntimeException("Unable to lookup service " + svc.getName()); } }); } } } } catch (Exception e) { throw new RuntimeException("Unable to bind session services", e); } */ Path basedirPath = Paths.get(getBasedir()); InjectMojo mojo = AnnotationSupport.findAnnotation(context.getElement().get(), InjectMojo.class) .orElse(null); Model defaultModel = Model.newBuilder() .groupId("myGroupId") .artifactId("myArtifactId") .version("1.0-SNAPSHOT") .packaging("jar") .build(Build.newBuilder() .directory(basedirPath.resolve("target").toString()) .outputDirectory(basedirPath.resolve("target/classes").toString()) .sources(List.of( Source.newBuilder() .scope("main") .lang("java") .directory(basedirPath .resolve("src/main/java") .toString()) .build(), Source.newBuilder() .scope("test") .lang("java") .directory(basedirPath .resolve("src/test/java") .toString()) .build())) .testOutputDirectory( basedirPath.resolve("target/test-classes").toString()) .build()) .build(); Path[] modelPath = new Path[] {null}; Model tmodel = null; if (mojo != null) { String pom = mojo.pom(); if (pom != null && !pom.isEmpty()) { try (Reader r = openPomUrl(context.getRequiredTestClass(), pom, modelPath)) { tmodel = new MavenStaxReader().read(r); } } else { Path pomPath = basedirPath.resolve("pom.xml"); if (Files.exists(pomPath)) { try (Reader r = Files.newBufferedReader(pomPath)) { tmodel = new MavenStaxReader().read(r); modelPath[0] = pomPath; } } } } Model model; if (tmodel == null) { model = defaultModel; } else { model = new MavenMerger().merge(tmodel, defaultModel, false, null); } tmodel = new DefaultModelPathTranslator(new DefaultPathTranslator()) .alignToBaseDirectory(tmodel, Paths.get(getBasedir()), null); context.getStore(ExtensionContext.Namespace.GLOBAL).put(Model.class, tmodel); // mojo execution // Map<Object, Object> map = getInjector().getContext().getContextData(); PluginDescriptor pluginDescriptor; ClassLoader classLoader = context.getRequiredTestClass().getClassLoader(); try (InputStream is = requireNonNull( classLoader.getResourceAsStream(getPluginDescriptorLocation()), "Unable to find plugin descriptor: " + getPluginDescriptorLocation()); Reader reader = new BufferedReader(new XmlStreamReader(is))) { // new InterpolationFilterReader(reader, map, "${", "}"); pluginDescriptor = new PluginDescriptorStaxReader().read(reader); } context.getStore(ExtensionContext.Namespace.GLOBAL).put(PluginDescriptor.class, pluginDescriptor); // for (ComponentDescriptor<?> desc : pluginDescriptor.getComponents()) { // getContainer().addComponentDescriptor(desc); // } @SuppressWarnings({"unused", "MagicNumber"}) class Foo { @Provides @Singleton @Priority(-10) private InternalSession createSession() { MojoTest mojoTest = context.getRequiredTestClass().getAnnotation(MojoTest.class); if (mojoTest != null && mojoTest.realSession()) { // Try to create a real session using ApiRunner without compile-time dependency try { Class<?> apiRunner = Class.forName("org.apache.maven.impl.standalone.ApiRunner"); Object session = apiRunner.getMethod("createSession").invoke(null); return (InternalSession) session; } catch (Throwable t) { // Explicit request: do not fall back; abort the test with details instead of mocking throw new org.opentest4j.TestAbortedException( "@MojoTest(realSession=true) requested but could not create a real session.", t); } } return SessionMock.getMockSession(getBasedir()); } @Provides @Singleton @Priority(-10) private Project createProject(InternalSession s) { ProjectStub stub = new ProjectStub(); if (!"pom".equals(model.getPackaging())) { ProducedArtifactStub artifact = new ProducedArtifactStub( model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging()); stub.setMainArtifact(artifact); } stub.setModel(model); stub.setBasedir(Paths.get(MojoExtension.getBasedir())); stub.setPomPath(modelPath[0]); s.getService(ArtifactManager.class).setPath(stub.getPomArtifact(), modelPath[0]); return stub; } @Provides @Singleton @Priority(-10) private MojoExecution createMojoExecution() { MojoExecutionStub mes = new MojoExecutionStub("executionId", null); if (mojo != null) { String goal = mojo.goal(); int idx = goal.lastIndexOf(':'); if (idx >= 0) { goal = goal.substring(idx + 1); } mes.setGoal(goal); for (MojoDescriptor md : pluginDescriptor.getMojos()) { if (goal.equals(md.getGoal())) { mes.setDescriptor(md); } } requireNonNull(mes.getDescriptor()); } PluginStub plugin = new PluginStub(); plugin.setDescriptor(pluginDescriptor); mes.setPlugin(plugin); return mes; } @Provides @Singleton @Priority(-10) private Log createLog() { return new DefaultLog(LoggerFactory.getLogger("anonymous")); } @Provides static RepositorySystemSupplier newRepositorySystemSupplier() { return new RepositorySystemSupplier(); } @Provides static RepositorySystem newRepositorySystem(RepositorySystemSupplier repositorySystemSupplier) { return repositorySystemSupplier.getRepositorySystem(); } @Provides @Priority(10) static RepositoryFactory newRepositoryFactory(Session session) { return session.getService(RepositoryFactory.class); } @Provides @Priority(10) static VersionParser newVersionParser(Session session) { return session.getService(VersionParser.class); } @Provides @Priority(10) static LocalRepositoryManager newLocalRepositoryManager(Session session) { return session.getService(LocalRepositoryManager.class); } @Provides @Priority(10) static ArtifactInstaller newArtifactInstaller(Session session) { return session.getService(ArtifactInstaller.class); } @Provides @Priority(10) static ArtifactDeployer newArtifactDeployer(Session session) { return session.getService(ArtifactDeployer.class); } @Provides @Priority(10) static ArtifactManager newArtifactManager(Session session) { return session.getService(ArtifactManager.class); } @Provides @Priority(10) static ProjectManager newProjectManager(Session session) { return session.getService(ProjectManager.class); } @Provides @Priority(10) static ArtifactFactory newArtifactFactory(Session session) { return session.getService(ArtifactFactory.class); } @Provides @Priority(10) static ProjectBuilder newProjectBuilder(Session session) { return session.getService(ProjectBuilder.class); } @Provides @Priority(10) static ModelXmlFactory newModelXmlFactory(Session session) { return session.getService(ModelXmlFactory.class); } } getInjector().bindInstance(Foo.class, new Foo()); getInjector().injectInstance(context.getRequiredTestInstance()); // SessionScope sessionScope = getInjector().getInstance(SessionScope.class); // sessionScope.enter(); // sessionScope.seed(Session.class, s); // sessionScope.seed(InternalSession.class, s); // MojoExecutionScope mojoExecutionScope = getInjector().getInstance(MojoExecutionScope.class); // mojoExecutionScope.enter(); // mojoExecutionScope.seed(Project.class, p); // mojoExecutionScope.seed(MojoExecution.class, me); } private Reader openPomUrl(Class<?> holder, String pom, Path[] modelPath) throws IOException { if (pom.startsWith("file:")) { Path path = Paths.get(getBasedir()).resolve(pom.substring("file:".length())); modelPath[0] = path; return Files.newBufferedReader(path); } else if (pom.startsWith("classpath:")) { URL url = holder.getResource(pom.substring("classpath:".length())); if (url == null) { throw new IllegalStateException("Unable to find pom on classpath: " + pom); } return new XmlStreamReader(url.openStream()); } else if (pom.contains("<project>")) { return new StringReader(pom); } else { Path path = Paths.get(getBasedir()).resolve(pom); modelPath[0] = path; return Files.newBufferedReader(path); } } protected String getPluginDescriptorLocation() { return "META-INF/maven/plugin.xml"; } protected String[] mojoCoordinates(String goal) throws Exception { if (goal.matches(".*:.*:.*:.*")) { return goal.split(":"); } else { Path pluginPom = Paths.get(getPluginBasedir(), "pom.xml"); Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(Files.newBufferedReader(pluginPom)); String artifactId = pluginPomDom.getChild("artifactId").getValue(); String groupId = resolveFromRootThenParent(pluginPomDom, "groupId"); String version = resolveFromRootThenParent(pluginPomDom, "version"); return new String[] {groupId, artifactId, version, goal}; } } private XmlNode finalizeConfig(XmlNode config, MojoDescriptor mojoDescriptor) { List<XmlNode> children = new ArrayList<>(); if (mojoDescriptor != null) { XmlNode defaultConfiguration; defaultConfiguration = MojoDescriptorCreator.convert(mojoDescriptor); for (Parameter parameter : mojoDescriptor.getParameters()) { XmlNode parameterConfiguration = config.child(parameter.getName()); if (parameterConfiguration == null) { parameterConfiguration = config.child(parameter.getAlias()); } XmlNode parameterDefaults = defaultConfiguration.child(parameter.getName()); parameterConfiguration = XmlNode.merge(parameterConfiguration, parameterDefaults, Boolean.TRUE); if (parameterConfiguration != null) { Map<String, String> attributes = new HashMap<>(parameterConfiguration.attributes()); // if (isEmpty(parameterConfiguration.getAttribute("implementation")) // && !isEmpty(parameter.getImplementation())) { // attributes.put("implementation", parameter.getImplementation()); // } parameterConfiguration = XmlNode.newInstance( parameter.getName(), parameterConfiguration.value(), attributes, parameterConfiguration.children(), parameterConfiguration.inputLocation()); children.add(parameterConfiguration); } } } return XmlNode.newInstance("configuration", null, null, children, null); } private static Optional<Xpp3Dom> child(Xpp3Dom element, String name) { return Optional.ofNullable(element.getChild(name)); } private static Stream<Xpp3Dom> children(Xpp3Dom element) { return Stream.of(element.getChildren()); } public static XmlNode extractPluginConfiguration(String artifactId, Xpp3Dom pomDom) throws Exception { Xpp3Dom pluginConfigurationElement = child(pomDom, "build") .flatMap(buildElement -> child(buildElement, "plugins")) .map(MojoExtension::children) .orElseGet(Stream::empty) .filter(e -> e.getChild("artifactId").getValue().equals(artifactId)) .findFirst() .flatMap(buildElement -> child(buildElement, "configuration")) .orElse(Xpp3DomBuilder.build(new StringReader("<configuration/>"))); return pluginConfigurationElement.getDom(); } /** * sometimes the parent element might contain the correct value so generalize that access * * TODO find out where this is probably done elsewhere */ private static String resolveFromRootThenParent(Xpp3Dom pluginPomDom, String element) throws Exception { return Optional.ofNullable(child(pluginPomDom, element).orElseGet(() -> child(pluginPomDom, "parent") .flatMap(e -> child(e, element)) .orElse(null))) .map(Xpp3Dom::getValue) .orElseThrow(() -> new Exception("unable to determine " + element)); } /** * Convenience method to obtain the value of a variable on a mojo that might not have a getter. * <br> * NOTE: the caller is responsible for casting to what the desired type is. */ public static Object getVariableValueFromObject(Object object, String variable) throws IllegalAccessException { Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); field.setAccessible(true); return field.get(object); } /** * Convenience method to obtain all variables and values from the mojo (including its superclasses) * <br> * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. */ public static Map<String, Object> getVariablesAndValuesFromObject(Object object) throws IllegalAccessException { return getVariablesAndValuesFromObject(object.getClass(), object); } /** * Convenience method to obtain all variables and values from the mojo (including its superclasses) * <br> * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. * * @return map of variable names and values */ public static Map<String, Object> getVariablesAndValuesFromObject(Class<?> clazz, Object object) throws IllegalAccessException { Map<String, Object> map = new HashMap<>(); Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (Field field : fields) { map.put(field.getName(), field.get(object)); } Class<?> superclass = clazz.getSuperclass(); if (!Object.class.equals(superclass)) { map.putAll(getVariablesAndValuesFromObject(superclass, object)); } return map; } /** * Convenience method to set values to variables in objects that don't have setters */ public static void setVariableValueToObject(Object object, String variable, Object value) throws IllegalAccessException { Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); requireNonNull(field, "Field " + variable + " not found"); field.setAccessible(true); field.set(object, value); } static class WrapEvaluator implements TypeAwareExpressionEvaluator { private final Injector injector; private final TypeAwareExpressionEvaluator evaluator; WrapEvaluator(Injector injector, TypeAwareExpressionEvaluator evaluator) { this.injector = injector; this.evaluator = evaluator; } @Override public Object evaluate(String expression) throws ExpressionEvaluationException { return evaluate(expression, null); } @Override public Object evaluate(String expression, Class<?> type) throws ExpressionEvaluationException { Object value = evaluator.evaluate(expression, type); if (value == null) { String expr = stripTokens(expression); if (expr != null) { try { value = injector.getInstance(Key.of(type, expr)); } catch (DIException e) { // nothing } } } return value; } private String stripTokens(String expr) { if (expr.startsWith("${") && expr.endsWith("}")) { return expr.substring(2, expr.length() - 1); } return null; } @Override public File alignToBaseDirectory(File path) { return evaluator.alignToBaseDirectory(path); } } /* private Scope getScopeInstanceOrNull(final Injector injector, final Binding<?> binding) { return binding.acceptScopingVisitor(new DefaultBindingScopingVisitor<Scope>() { @Override public Scope visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) { throw new RuntimeException(String.format( "I don't know how to handle the scopeAnnotation: %s", scopeAnnotation.getCanonicalName())); } @Override public Scope visitNoScoping() { if (binding instanceof LinkedKeyBinding) { Binding<?> childBinding = injector.getBinding(((LinkedKeyBinding) binding).getLinkedKey()); return getScopeInstanceOrNull(injector, childBinding); } return null; } @Override public Scope visitEagerSingleton() { return Scopes.SINGLETON; } public Scope visitScope(Scope scope) { return scope; } }); }*/ }
apache/qpid-broker-j
36,069
systests/qpid-systests-jms_1.1/src/test/java/org/apache/qpid/systests/jms_1_1/extensions/acl/MessagingACLTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.qpid.systests.jms_1_1.extensions.acl; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TemporaryQueue; import javax.jms.TemporaryTopic; import javax.jms.TextMessage; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.logging.EventLoggerProvider; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.Group; import org.apache.qpid.server.model.GroupMember; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.security.access.config.AclFileParser; import org.apache.qpid.server.security.access.config.Rule; import org.apache.qpid.server.security.access.config.RuleSet; import org.apache.qpid.server.security.access.plugins.AclRule; import org.apache.qpid.server.security.access.plugins.RuleBasedVirtualHostAccessControlProvider; import org.apache.qpid.server.security.group.GroupProviderImpl; import org.apache.qpid.systests.JmsTestBase; public class MessagingACLTest extends JmsTestBase { private static final Logger LOGGER = LoggerFactory.getLogger(MessagingACLTest.class); private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final String USER1 = "guest"; private static final String USER1_PASSWORD = "guest"; private static final String USER2 = "admin"; private static final String USER2_PASSWORD = "admin"; private static final String RULE_BASED_VIRTUAL_HOST_ACCESS_CONTROL_PROVIDER_TYPE = "org.apache.qpid.RuleBaseVirtualHostAccessControlProvider"; private static final String EXCHANGE_TYPE = "org.apache.qpid.Exchange"; @Test public void testAccessAuthorizedSuccess() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { assertConnection(connection); } finally { connection.close(); } } @Test public void testAccessNoRightsFailure() throws Exception { configureACL(String.format("ACL DENY-LOG %s ACCESS VIRTUALHOST", USER1)); try { getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); fail("Connection was created."); } catch (JMSException e) { assertAccessDeniedException(e); } } @Test public void testAccessVirtualHostWithName() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST name='%s'", USER1, getVirtualHostName()), String.format("ACL DENY-LOG %s ACCESS VIRTUALHOST name='%s'", USER2, getVirtualHostName())); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { assertConnection(connection); } finally { connection.close(); } try { getConnectionBuilder().setUsername(USER2).setPassword(USER2_PASSWORD).build(); fail("Access should be denied"); } catch (JMSException e) { assertAccessDeniedException(e); } } @Test public void testAccessVirtualHostWildCard() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST name='*'", USER1), String.format("ACL DENY-LOG %s ACCESS VIRTUALHOST name='*'", USER2)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { assertConnection(connection); } finally { connection.close(); } try { getConnectionBuilder().setUsername(USER2).setPassword(USER2_PASSWORD).build(); fail("Access should be denied"); } catch (JMSException e) { assertAccessDeniedException(e); } } @Test public void testConsumeFromTempQueueSuccess() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s CREATE QUEUE temporary=\"true\"", USER1), String.format("ACL ALLOW-LOG %s CONSUME QUEUE temporary=\"true\"", USER1), isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE name=\"*\"", USER1) : ""); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); session.createConsumer(session.createTemporaryQueue()).close(); } finally { connection.close(); } } @Test public void testConsumeFromTempQueueFailure() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s CREATE QUEUE temporary=\"true\"", USER1), String.format("ACL DENY-LOG %s CONSUME QUEUE temporary=\"true\"", USER1), isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE name=\"*\"", USER1) : ""); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); TemporaryQueue temporaryQueue = session.createTemporaryQueue(); try { session.createConsumer(temporaryQueue); fail("Exception is not thrown"); } catch (JMSException e) { // pass } } finally { try { connection.close(); } catch (Exception e) { LOGGER.error("Unexpected exception on connection close", e); } } } @Test public void testConsumeOwnQueueSuccess() throws Exception { final String queueName = "user1Queue"; assumeTrue(Objects.equals(getBrokerAdmin().getValidUsername(), USER1)); createQueue(queueName); Map<String, Object> queueAttributes = readEntityUsingAmqpManagement(queueName, "org.apache.qpid.Queue", true); assertThat("Test prerequiste not met, queue belongs to unexpected user", queueAttributes.get(ConfiguredObject.CREATED_BY), is(equalTo(USER1))); configureACL("ACL ALLOW-LOG ALL ACCESS VIRTUALHOST", "ACL ALLOW-LOG OWNER CONSUME QUEUE", "ACL DENY-LOG ALL CONSUME QUEUE"); final String queueAddress = String.format(isLegacyClient() ? "ADDR:%s; {create:never}" : "%s", queueName); Connection queueOwnerCon = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session queueOwnerSession = queueOwnerCon.createSession(false, Session.AUTO_ACKNOWLEDGE); final Queue queue = queueOwnerSession.createQueue(queueAddress); queueOwnerSession.createConsumer(queue).close(); } finally { queueOwnerCon.close(); } Connection otherUserCon = getConnectionBuilder().setUsername(USER2).setPassword(USER2_PASSWORD).build(); try { Session otherUserSession = otherUserCon.createSession(false, Session.AUTO_ACKNOWLEDGE); try { otherUserSession.createConsumer(otherUserSession.createQueue(queueAddress)).close(); fail("Exception not thrown"); } catch (JMSException e) { final String expectedMessage = Set.of(Protocol.AMQP_1_0, Protocol.AMQP_0_10).contains(getProtocol()) ? "Permission CREATE is denied for : Consumer" : "403(access refused)"; assertJMSExceptionMessageContains(e, expectedMessage); } } finally { otherUserCon.close(); } } @Test public void testConsumeFromTempTopicSuccess() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s CREATE QUEUE temporary=\"true\"", USER1), String.format("ACL ALLOW-LOG %s CONSUME QUEUE temporary=\"true\"", USER1), String.format(isLegacyClient() ? "ACL ALLOW-LOG %s BIND EXCHANGE name=\"amq.topic\"" : "ACL ALLOW-LOG %s BIND EXCHANGE temporary=\"true\"", USER1)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); TemporaryTopic temporaryTopic = session.createTemporaryTopic(); session.createConsumer(temporaryTopic); } finally { connection.close(); } } @Test public void testConsumeFromNamedQueueValid() throws Exception { final String queueName = getTestName(); Queue queue = createQueue(queueName); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s CONSUME QUEUE name=\"%s\"", USER1, queueName), isLegacyClient() ? String.format("ACL ALLOW-LOG %s CREATE QUEUE name=\"%s\"", USER1, queueName) : "", isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE name=\"*\" routingKey=\"%s\"", USER1, queueName) : ""); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); session.createConsumer(queue).close(); } finally { connection.close(); } } @Test public void testConsumeFromNamedQueueFailure() throws Exception { String queueName = getTestName(); Queue queue = createQueue(queueName); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL DENY-LOG %s CONSUME QUEUE name=\"%s\"", USER1, queueName), isLegacyClient() ? String.format("ACL ALLOW-LOG %s CREATE QUEUE name=\"%s\"", USER1, queueName) : "", isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE name=\"*\" routingKey=\"%s\"", USER1, queueName) : ""); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); try { session.createConsumer(queue); fail("Test failed as consumer was created."); } catch (JMSException e) { // pass } } finally { connection.close(); } } @Test public void testCreateTemporaryQueueSuccess() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s CREATE QUEUE temporary=\"true\"", USER1), isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE name=\"*\" temporary=true", USER1) : ""); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = session.createTemporaryQueue(); assertNotNull(queue); } finally { connection.close(); } } // For AMQP 1.0 the server causes a temporary instance of the fanout exchange to come into being. // For early AMQP version, there are no server side objects created as amq.topic is used. @Test public void testCreateTempTopicSuccess() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryTopic temporaryTopic = session.createTemporaryTopic(); assertNotNull(temporaryTopic); } finally { connection.close(); } } @Test public void testCreateTemporaryQueueFailed() throws Exception { assumeTrue(!Objects.equals(getProtocol(), Protocol.AMQP_1_0), "QPID-7919"); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL DENY-LOG %s CREATE QUEUE temporary=\"true\"", USER1)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); try { session.createTemporaryQueue(); fail("Test failed as creation succeeded."); } catch (JMSException e) { assertJMSExceptionMessageContains(e, "Permission CREATE is denied for : Queue"); } } finally { connection.close(); } } @Test public void testPublishUsingTransactionSuccess() throws Exception { String queueName = getTestName(); Queue queue = createQueue(queueName); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format(isLegacyClient() ? "ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.direct\" routingKey=\"%s\"" : "ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"\" routingKey=\"%s\"", USER1, queueName)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer sender = session.createProducer(queue); sender.send(session.createTextMessage("test")); session.commit(); } finally { connection.close(); } } @Test public void testPublishToExchangeUsingTransactionSuccess() throws Exception { String queueName = getTestName(); createQueue(queueName); final Map<String, Object> bindingArguments = new HashMap<>(); bindingArguments.put("destination", queueName); bindingArguments.put("bindingKey", queueName); performOperationUsingAmqpManagement("amq.direct", "bind", EXCHANGE_TYPE, bindingArguments); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.direct\" routingKey=\"%s\"", USER1, queueName)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); String address = String.format(isLegacyClient() ? "ADDR:amq.direct/%s" : "amq.direct/%s", queueName); Queue queue = session.createQueue(address); MessageProducer sender = session.createProducer(queue); sender.send(session.createTextMessage("test")); session.commit(); } finally { connection.close(); } } @Test public void testRequestResponseSuccess() throws Exception { String queueName = getTestName(); Queue queue = createQueue(queueName); String groupName = "messaging-users"; createGroupProvider(groupName, USER1, USER2); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", groupName), String.format("ACL ALLOW-LOG %s CONSUME QUEUE name=\"%s\"", USER1, queueName), String.format("ACL ALLOW-LOG %s CONSUME QUEUE temporary=true", USER2), String.format("ACL ALLOW-LOG %s CREATE QUEUE temporary=true", USER2), isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE name=\"amq.direct\" temporary=true", USER2) : String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"\" routingKey=\"TempQueue*\"", USER1), isLegacyClient() ? String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.direct\" routingKey=\"%s\"", USER2, queueName) : String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"\" routingKey=\"%s\"", USER2, queueName), isLegacyClient() ? String.format("ACL ALLOW-LOG %s CREATE QUEUE name=\"%s\"", USER1, queueName) : "", isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE", USER1) : "", isLegacyClient() ? String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.direct\" routingKey=\"TempQueue*\"", USER1) : "" ); Connection responderConnection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session responderSession = responderConnection.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer requestConsumer = responderSession.createConsumer(queue); responderConnection.start(); Connection requesterConnection = getConnectionBuilder().setUsername(USER2).setPassword(USER2_PASSWORD).build(); try { Session requesterSession = requesterConnection.createSession(true, Session.SESSION_TRANSACTED); Queue responseQueue = requesterSession.createTemporaryQueue(); MessageConsumer responseConsumer = requesterSession.createConsumer(responseQueue); requesterConnection.start(); Message request = requesterSession.createTextMessage("Request"); request.setJMSReplyTo(responseQueue); requesterSession.createProducer(queue).send(request); requesterSession.commit(); Message receivedRequest = requestConsumer.receive(getReceiveTimeout()); assertNotNull(receivedRequest, "Request is not received"); assertNotNull(receivedRequest.getJMSReplyTo(), "Request should have Reply-To"); MessageProducer responder = responderSession.createProducer(receivedRequest.getJMSReplyTo()); responder.send(responderSession.createTextMessage("Response")); responderSession.commit(); Message receivedResponse = responseConsumer.receive(getReceiveTimeout()); requesterSession.commit(); assertNotNull(receivedResponse, "Response is not received"); assertEquals("Response", ((TextMessage) receivedResponse).getText(), "Unexpected response is received"); } finally { requesterConnection.close(); } } finally { responderConnection.close(); } } @Test public void testPublishToTempTopicSuccess() throws Exception { configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), isLegacyClient() ? String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.topic\"", USER1) : String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE temporary=\"true\"", USER1)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); connection.start(); TemporaryTopic temporaryTopic = session.createTemporaryTopic(); MessageProducer producer = session.createProducer(temporaryTopic); producer.send(session.createMessage()); session.commit(); } finally { connection.close(); } } @Test public void testFirewallAllow() throws Exception { configureACL(String.format("ACL ALLOW %s ACCESS VIRTUALHOST from_network=\"127.0.0.1\"", USER1)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { assertConnection(connection); } finally { connection.close(); } } @Test public void testAllAllowed() throws Exception { configureACL("ACL ALLOW ALL ALL"); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { assertConnection(connection); } finally { connection.close(); } } @Test public void testFirewallDeny() throws Exception { configureACL(String.format("ACL DENY %s ACCESS VIRTUALHOST from_network=\"127.0.0.1\"", USER1)); try { getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); fail("We expected the connection to fail"); } catch (JMSException e) { // pass } } @Test public void testPublishToDefaultExchangeSuccess() throws Exception { assumeTrue(!Objects.equals(getProtocol(), Protocol.AMQP_1_0), "Test not applicable for AMQP 1.0"); String queueName = getTestName(); createQueue(queueName); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"\" routingKey=\"%s\"", USER1, queueName)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer sender = session.createProducer(session.createQueue(String.format("ADDR: %s", queueName))); sender.send(session.createTextMessage("test")); session.commit(); } finally { connection.close(); } } @Test public void testPublishToDefaultExchangeFailure() throws Exception { assumeTrue(!Objects.equals(getProtocol(), Protocol.AMQP_1_0), "Test not applicable for AMQP 1.0"); String queueName = getTestName(); createQueue(queueName); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL DENY-LOG %s PUBLISH EXCHANGE name=\"\" routingKey=\"%s\"", USER1, queueName)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer sender = session.createProducer(session.createQueue(String.format("ADDR: %s", queueName))); sender.send(session.createTextMessage("test")); session.commit(); fail("Sending to the anonymousExchange without permission should fail"); } catch (JMSException e) { assertJMSExceptionMessageContains(e, "Access denied to publish to default exchange"); } finally { connection.close(); } } @Test public void testAnonymousProducerFailsToSendMessageIntoDeniedDestination() throws Exception { final String allowedDestinationName = "example.RequestQueue"; final String deniedDestinationName = "deniedQueue"; createQueue(allowedDestinationName); createQueue(deniedDestinationName); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format(isLegacyClient() ? "ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.direct\" routingKey=\"%s\"" : "ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"\" routingKey=\"%s\"", USER1, allowedDestinationName), String.format("ACL DENY-LOG %s PUBLISH EXCHANGE name=\"*\" routingKey=\"%s\"", USER1, deniedDestinationName)); Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = session.createProducer(null); producer.send(session.createQueue(allowedDestinationName), session.createTextMessage("test1")); session.commit(); } finally { connection.close(); } Connection connection2 = getConnectionBuilder().setSyncPublish(true).setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection2.createSession(true, Session.SESSION_TRANSACTED); try { MessageProducer producer = session.createProducer(null); producer.send(session.createQueue(deniedDestinationName), session.createTextMessage("test2")); fail("Sending should fail"); } catch (JMSException e) { assertJMSExceptionMessageContains(e, String.format( "Permission PERFORM_ACTION(publish) is denied for : %s", (!isLegacyClient() ? "Queue" : "Exchange"))); } try { session.commit(); fail("Commit should fail"); } catch (JMSException e) { // pass } } finally { connection2.close(); } } @Test public void testPublishIntoDeniedDestinationFails() throws Exception { final String deniedDestinationName = "deniedQueue"; createQueue(deniedDestinationName); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL DENY-LOG %s PUBLISH EXCHANGE name=\"*\" routingKey=\"%s\"", USER1, deniedDestinationName)); Connection connection = getConnectionBuilder().setSyncPublish(true).setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = session.createProducer(session.createQueue(deniedDestinationName)); producer.send(session.createTextMessage("test")); fail("Sending should fail"); } catch (JMSException e) { assertJMSExceptionMessageContains(e, String.format( "Permission PERFORM_ACTION(publish) is denied for : %s", (!isLegacyClient() ? "Queue" : "Exchange"))); } } @Test public void testCreateNamedQueueFailure() throws Exception { assumeTrue(!Objects.equals(getProtocol(), Protocol.AMQP_1_0), "Test not applicable for AMQP 1.0"); String queueName = getTestName(); configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1), String.format("ACL ALLOW-LOG %s CREATE QUEUE name=\"%s\"", USER1, queueName), isLegacyClient() ? String.format("ACL ALLOW-LOG %s BIND EXCHANGE name=\"*\" routingKey=\"%s\"", USER1, queueName) : ""); Connection connection = getConnectionBuilder().setSyncPublish(true).setUsername(USER1).setPassword(USER1_PASSWORD).build(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { session.createConsumer(session.createQueue("IllegalQueue")); fail("Test failed as Queue creation succeeded."); } catch (JMSException e) { assertJMSExceptionMessageContains(e, "Permission CREATE is denied for : Queue"); } } finally { connection.close(); } } private void assertJMSExceptionMessageContains(final JMSException e, final String expectedMessage) { Set<Throwable> examined = new HashSet<>(); Throwable current = e; do { if (current.getMessage().contains(expectedMessage)) { return; } examined.add(current); current = current.getCause(); } while (current != null && !examined.contains(current)); e.printStackTrace(); fail(String.format("Unexpected message. Root exception : %s. Expected root or underlying(s) to contain : %s", e.getMessage(), expectedMessage)); } private void configureACL(String... rules) throws Exception { EventLoggerProvider eventLoggerProvider = mock(EventLoggerProvider.class); EventLogger eventLogger = mock(EventLogger.class); when(eventLoggerProvider.getEventLogger()).thenReturn(eventLogger); List<AclRule> aclRules = new ArrayList<>(); try(StringReader stringReader = new StringReader(Arrays.stream(rules).collect(Collectors.joining(LINE_SEPARATOR)))) { RuleSet ruleSet = AclFileParser.parse(stringReader, eventLoggerProvider); for (final Rule rule: ruleSet) { aclRules.add(rule.asAclRule()); } } configureACL(aclRules.toArray(new AclRule[aclRules.size()])); } private void configureACL(AclRule... rules) throws Exception { final String serializedRules = new ObjectMapper().writeValueAsString(rules); final Map<String, Object> attributes = new HashMap<>(); attributes.put(RuleBasedVirtualHostAccessControlProvider.RULES, serializedRules); attributes.put(RuleBasedVirtualHostAccessControlProvider.DEFAULT_RESULT, "DENIED"); createEntityUsingAmqpManagement("acl", RULE_BASED_VIRTUAL_HOST_ACCESS_CONTROL_PROVIDER_TYPE, attributes); } private void createGroupProvider(final String groupName, final String... groupMembers) throws Exception { String groupProviderName = "groups"; Connection connection = getConnectionBuilder().setVirtualHost("$management").build(); try { connection.start(); createEntity(groupProviderName, GroupProviderImpl.class.getName(), Collections.emptyMap(), connection); createEntity(groupName, Group.class.getName(), Collections.singletonMap("object-path", groupProviderName), connection); for (String groupMember: groupMembers) { createEntity(groupMember, GroupMember.class.getName(), Collections.singletonMap("object-path", groupProviderName + "/" + groupName), connection); } } finally { connection.close(); } } private void assertConnection(final Connection connection) throws JMSException { assertNotNull(connection.createSession(false, Session.AUTO_ACKNOWLEDGE), "create session should be successful"); } private void assertAccessDeniedException(JMSException e) throws Exception { assertTrue(e.getMessage().contains("Permission PERFORM_ACTION(connect) is denied"), "Unexpected exception message:" + e.getMessage()); if (getProtocol() == Protocol.AMQP_1_0) { assertTrue(e.getMessage().contains("amqp:not-allowed"), "Unexpected error condition reported:" + e.getMessage()); } } private boolean isLegacyClient() { return getProtocol() != Protocol.AMQP_1_0; } }
googleapis/google-api-java-client-services
36,601
clients/google-api-services-compute/alpha/1.28.0/com/google/api/services/compute/model/Firewall.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Represents a Firewall Rule resource. * * Firewall rules allow or deny ingress traffic to, and egress traffic from your instances. For more * information, read Firewall rules. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Firewall extends com.google.api.client.json.GenericJson { /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Allowed> allowed; static { // hack to force ProGuard to consider Allowed used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Allowed.class); } /** * [Output Only] Creation timestamp in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Denied> denied; static { // hack to force ProGuard to consider Denied used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Denied.class); } /** * An optional description of this resource. Provide this field when you create the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinationRanges; /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String direction; /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean disabled; /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableLogging; /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Stackdriver. * The value may be {@code null}. */ @com.google.api.client.util.Key private FirewallLogConfig logConfig; /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String network; /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer priority; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] Server-defined URL for this resource with the resource id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLinkWithId; /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceRanges; /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceServiceAccounts; /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceTags; /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetServiceAccounts; /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetTags; /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @return value or {@code null} for none */ public java.util.List<Allowed> getAllowed() { return allowed; } /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @param allowed allowed or {@code null} for none */ public Firewall setAllowed(java.util.List<Allowed> allowed) { this.allowed = allowed; return this; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Firewall setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @return value or {@code null} for none */ public java.util.List<Denied> getDenied() { return denied; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @param denied denied or {@code null} for none */ public Firewall setDenied(java.util.List<Denied> denied) { this.denied = denied; return this; } /** * An optional description of this resource. Provide this field when you create the resource. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * An optional description of this resource. Provide this field when you create the resource. * @param description description or {@code null} for none */ public Firewall setDescription(java.lang.String description) { this.description = description; return this; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getDestinationRanges() { return destinationRanges; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * @param destinationRanges destinationRanges or {@code null} for none */ public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) { this.destinationRanges = destinationRanges; return this; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @return value or {@code null} for none */ public java.lang.String getDirection() { return direction; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @param direction direction or {@code null} for none */ public Firewall setDirection(java.lang.String direction) { this.direction = direction; return this; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @return value or {@code null} for none */ public java.lang.Boolean getDisabled() { return disabled; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @param disabled disabled or {@code null} for none */ public Firewall setDisabled(java.lang.Boolean disabled) { this.disabled = disabled; return this; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. * @return value or {@code null} for none */ public java.lang.Boolean getEnableLogging() { return enableLogging; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. * @param enableLogging enableLogging or {@code null} for none */ public Firewall setEnableLogging(java.lang.Boolean enableLogging) { this.enableLogging = enableLogging; return this; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @param id id or {@code null} for none */ public Firewall setId(java.math.BigInteger id) { this.id = id; return this; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @param kind kind or {@code null} for none */ public Firewall setKind(java.lang.String kind) { this.kind = kind; return this; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Stackdriver. * @return value or {@code null} for none */ public FirewallLogConfig getLogConfig() { return logConfig; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Stackdriver. * @param logConfig logConfig or {@code null} for none */ public Firewall setLogConfig(FirewallLogConfig logConfig) { this.logConfig = logConfig; return this; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @param name name or {@code null} for none */ public Firewall setName(java.lang.String name) { this.name = name; return this; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * @return value or {@code null} for none */ public java.lang.String getNetwork() { return network; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * @param network network or {@code null} for none */ public Firewall setNetwork(java.lang.String network) { this.network = network; return this; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @return value or {@code null} for none */ public java.lang.Integer getPriority() { return priority; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @param priority priority or {@code null} for none */ public Firewall setPriority(java.lang.Integer priority) { this.priority = priority; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Firewall setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @return value or {@code null} for none */ public java.lang.String getSelfLinkWithId() { return selfLinkWithId; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @param selfLinkWithId selfLinkWithId or {@code null} for none */ public Firewall setSelfLinkWithId(java.lang.String selfLinkWithId) { this.selfLinkWithId = selfLinkWithId; return this; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceRanges() { return sourceRanges; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * @param sourceRanges sourceRanges or {@code null} for none */ public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) { this.sourceRanges = sourceRanges; return this; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceServiceAccounts() { return sourceServiceAccounts; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none */ public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) { this.sourceServiceAccounts = sourceServiceAccounts; return this; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceTags() { return sourceTags; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @param sourceTags sourceTags or {@code null} for none */ public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) { this.sourceTags = sourceTags; return this; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetServiceAccounts() { return targetServiceAccounts; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @param targetServiceAccounts targetServiceAccounts or {@code null} for none */ public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) { this.targetServiceAccounts = targetServiceAccounts; return this; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetTags() { return targetTags; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @param targetTags targetTags or {@code null} for none */ public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) { this.targetTags = targetTags; return this; } @Override public Firewall set(String fieldName, Object value) { return (Firewall) super.set(fieldName, value); } @Override public Firewall clone() { return (Firewall) super.clone(); } /** * Model definition for FirewallAllowed. */ public static final class Allowed extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Allowed setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @param ports ports or {@code null} for none */ public Allowed setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Allowed set(String fieldName, Object value) { return (Allowed) super.set(fieldName, value); } @Override public Allowed clone() { return (Allowed) super.clone(); } } /** * Model definition for FirewallDenied. */ public static final class Denied extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Denied setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @param ports ports or {@code null} for none */ public Denied setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Denied set(String fieldName, Object value) { return (Denied) super.set(fieldName, value); } @Override public Denied clone() { return (Denied) super.clone(); } } }
googleapis/google-api-java-client-services
36,601
clients/google-api-services-compute/alpha/1.29.2/com/google/api/services/compute/model/Firewall.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Represents a Firewall Rule resource. * * Firewall rules allow or deny ingress traffic to, and egress traffic from your instances. For more * information, read Firewall rules. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Firewall extends com.google.api.client.json.GenericJson { /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Allowed> allowed; static { // hack to force ProGuard to consider Allowed used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Allowed.class); } /** * [Output Only] Creation timestamp in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Denied> denied; static { // hack to force ProGuard to consider Denied used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Denied.class); } /** * An optional description of this resource. Provide this field when you create the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinationRanges; /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String direction; /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean disabled; /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableLogging; /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Stackdriver. * The value may be {@code null}. */ @com.google.api.client.util.Key private FirewallLogConfig logConfig; /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String network; /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer priority; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] Server-defined URL for this resource with the resource id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLinkWithId; /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceRanges; /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceServiceAccounts; /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceTags; /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetServiceAccounts; /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetTags; /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @return value or {@code null} for none */ public java.util.List<Allowed> getAllowed() { return allowed; } /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @param allowed allowed or {@code null} for none */ public Firewall setAllowed(java.util.List<Allowed> allowed) { this.allowed = allowed; return this; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Firewall setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @return value or {@code null} for none */ public java.util.List<Denied> getDenied() { return denied; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @param denied denied or {@code null} for none */ public Firewall setDenied(java.util.List<Denied> denied) { this.denied = denied; return this; } /** * An optional description of this resource. Provide this field when you create the resource. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * An optional description of this resource. Provide this field when you create the resource. * @param description description or {@code null} for none */ public Firewall setDescription(java.lang.String description) { this.description = description; return this; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getDestinationRanges() { return destinationRanges; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * @param destinationRanges destinationRanges or {@code null} for none */ public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) { this.destinationRanges = destinationRanges; return this; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @return value or {@code null} for none */ public java.lang.String getDirection() { return direction; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @param direction direction or {@code null} for none */ public Firewall setDirection(java.lang.String direction) { this.direction = direction; return this; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @return value or {@code null} for none */ public java.lang.Boolean getDisabled() { return disabled; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @param disabled disabled or {@code null} for none */ public Firewall setDisabled(java.lang.Boolean disabled) { this.disabled = disabled; return this; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. * @return value or {@code null} for none */ public java.lang.Boolean getEnableLogging() { return enableLogging; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported to Stackdriver. * @param enableLogging enableLogging or {@code null} for none */ public Firewall setEnableLogging(java.lang.Boolean enableLogging) { this.enableLogging = enableLogging; return this; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @param id id or {@code null} for none */ public Firewall setId(java.math.BigInteger id) { this.id = id; return this; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @param kind kind or {@code null} for none */ public Firewall setKind(java.lang.String kind) { this.kind = kind; return this; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Stackdriver. * @return value or {@code null} for none */ public FirewallLogConfig getLogConfig() { return logConfig; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Stackdriver. * @param logConfig logConfig or {@code null} for none */ public Firewall setLogConfig(FirewallLogConfig logConfig) { this.logConfig = logConfig; return this; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @param name name or {@code null} for none */ public Firewall setName(java.lang.String name) { this.name = name; return this; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * @return value or {@code null} for none */ public java.lang.String getNetwork() { return network; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * @param network network or {@code null} for none */ public Firewall setNetwork(java.lang.String network) { this.network = network; return this; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @return value or {@code null} for none */ public java.lang.Integer getPriority() { return priority; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @param priority priority or {@code null} for none */ public Firewall setPriority(java.lang.Integer priority) { this.priority = priority; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Firewall setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @return value or {@code null} for none */ public java.lang.String getSelfLinkWithId() { return selfLinkWithId; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @param selfLinkWithId selfLinkWithId or {@code null} for none */ public Firewall setSelfLinkWithId(java.lang.String selfLinkWithId) { this.selfLinkWithId = selfLinkWithId; return this; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceRanges() { return sourceRanges; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * @param sourceRanges sourceRanges or {@code null} for none */ public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) { this.sourceRanges = sourceRanges; return this; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceServiceAccounts() { return sourceServiceAccounts; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none */ public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) { this.sourceServiceAccounts = sourceServiceAccounts; return this; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceTags() { return sourceTags; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @param sourceTags sourceTags or {@code null} for none */ public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) { this.sourceTags = sourceTags; return this; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetServiceAccounts() { return targetServiceAccounts; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @param targetServiceAccounts targetServiceAccounts or {@code null} for none */ public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) { this.targetServiceAccounts = targetServiceAccounts; return this; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetTags() { return targetTags; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @param targetTags targetTags or {@code null} for none */ public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) { this.targetTags = targetTags; return this; } @Override public Firewall set(String fieldName, Object value) { return (Firewall) super.set(fieldName, value); } @Override public Firewall clone() { return (Firewall) super.clone(); } /** * Model definition for FirewallAllowed. */ public static final class Allowed extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Allowed setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @param ports ports or {@code null} for none */ public Allowed setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Allowed set(String fieldName, Object value) { return (Allowed) super.set(fieldName, value); } @Override public Allowed clone() { return (Allowed) super.clone(); } } /** * Model definition for FirewallDenied. */ public static final class Denied extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Denied setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @param ports ports or {@code null} for none */ public Denied setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Denied set(String fieldName, Object value) { return (Denied) super.set(fieldName, value); } @Override public Denied clone() { return (Denied) super.clone(); } } }
googleapis/google-cloud-java
36,340
java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/ListSipTrunksResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2beta1/sip_trunk.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * The response message for * [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2beta1.SipTrunks.ListSipTrunks]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListSipTrunksResponse} */ public final class ListSipTrunksResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.ListSipTrunksResponse) ListSipTrunksResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListSipTrunksResponse.newBuilder() to construct. private ListSipTrunksResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListSipTrunksResponse() { sipTrunks_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListSipTrunksResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.SipTrunkProto .internal_static_google_cloud_dialogflow_v2beta1_ListSipTrunksResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.SipTrunkProto .internal_static_google_cloud_dialogflow_v2beta1_ListSipTrunksResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse.class, com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse.Builder.class); } public static final int SIP_TRUNKS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dialogflow.v2beta1.SipTrunk> sipTrunks_; /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.v2beta1.SipTrunk> getSipTrunksList() { return sipTrunks_; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.SipTrunkOrBuilder> getSipTrunksOrBuilderList() { return sipTrunks_; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ @java.lang.Override public int getSipTrunksCount() { return sipTrunks_.size(); } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SipTrunk getSipTrunks(int index) { return sipTrunks_.get(index); } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SipTrunkOrBuilder getSipTrunksOrBuilder(int index) { return sipTrunks_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < sipTrunks_.size(); i++) { output.writeMessage(1, sipTrunks_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < sipTrunks_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, sipTrunks_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse other = (com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse) obj; if (!getSipTrunksList().equals(other.getSipTrunksList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getSipTrunksCount() > 0) { hash = (37 * hash) + SIP_TRUNKS_FIELD_NUMBER; hash = (53 * hash) + getSipTrunksList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response message for * [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2beta1.SipTrunks.ListSipTrunks]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListSipTrunksResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.ListSipTrunksResponse) com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.SipTrunkProto .internal_static_google_cloud_dialogflow_v2beta1_ListSipTrunksResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.SipTrunkProto .internal_static_google_cloud_dialogflow_v2beta1_ListSipTrunksResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse.class, com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (sipTrunksBuilder_ == null) { sipTrunks_ = java.util.Collections.emptyList(); } else { sipTrunks_ = null; sipTrunksBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.SipTrunkProto .internal_static_google_cloud_dialogflow_v2beta1_ListSipTrunksResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse build() { com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse buildPartial() { com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse result = new com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse result) { if (sipTrunksBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { sipTrunks_ = java.util.Collections.unmodifiableList(sipTrunks_); bitField0_ = (bitField0_ & ~0x00000001); } result.sipTrunks_ = sipTrunks_; } else { result.sipTrunks_ = sipTrunksBuilder_.build(); } } private void buildPartial0(com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse) { return mergeFrom((com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse other) { if (other == com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse.getDefaultInstance()) return this; if (sipTrunksBuilder_ == null) { if (!other.sipTrunks_.isEmpty()) { if (sipTrunks_.isEmpty()) { sipTrunks_ = other.sipTrunks_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSipTrunksIsMutable(); sipTrunks_.addAll(other.sipTrunks_); } onChanged(); } } else { if (!other.sipTrunks_.isEmpty()) { if (sipTrunksBuilder_.isEmpty()) { sipTrunksBuilder_.dispose(); sipTrunksBuilder_ = null; sipTrunks_ = other.sipTrunks_; bitField0_ = (bitField0_ & ~0x00000001); sipTrunksBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSipTrunksFieldBuilder() : null; } else { sipTrunksBuilder_.addAllMessages(other.sipTrunks_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.dialogflow.v2beta1.SipTrunk m = input.readMessage( com.google.cloud.dialogflow.v2beta1.SipTrunk.parser(), extensionRegistry); if (sipTrunksBuilder_ == null) { ensureSipTrunksIsMutable(); sipTrunks_.add(m); } else { sipTrunksBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.dialogflow.v2beta1.SipTrunk> sipTrunks_ = java.util.Collections.emptyList(); private void ensureSipTrunksIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { sipTrunks_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.SipTrunk>(sipTrunks_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.SipTrunk, com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder, com.google.cloud.dialogflow.v2beta1.SipTrunkOrBuilder> sipTrunksBuilder_; /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2beta1.SipTrunk> getSipTrunksList() { if (sipTrunksBuilder_ == null) { return java.util.Collections.unmodifiableList(sipTrunks_); } else { return sipTrunksBuilder_.getMessageList(); } } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public int getSipTrunksCount() { if (sipTrunksBuilder_ == null) { return sipTrunks_.size(); } else { return sipTrunksBuilder_.getCount(); } } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.SipTrunk getSipTrunks(int index) { if (sipTrunksBuilder_ == null) { return sipTrunks_.get(index); } else { return sipTrunksBuilder_.getMessage(index); } } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder setSipTrunks(int index, com.google.cloud.dialogflow.v2beta1.SipTrunk value) { if (sipTrunksBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSipTrunksIsMutable(); sipTrunks_.set(index, value); onChanged(); } else { sipTrunksBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder setSipTrunks( int index, com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder builderForValue) { if (sipTrunksBuilder_ == null) { ensureSipTrunksIsMutable(); sipTrunks_.set(index, builderForValue.build()); onChanged(); } else { sipTrunksBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder addSipTrunks(com.google.cloud.dialogflow.v2beta1.SipTrunk value) { if (sipTrunksBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSipTrunksIsMutable(); sipTrunks_.add(value); onChanged(); } else { sipTrunksBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder addSipTrunks(int index, com.google.cloud.dialogflow.v2beta1.SipTrunk value) { if (sipTrunksBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSipTrunksIsMutable(); sipTrunks_.add(index, value); onChanged(); } else { sipTrunksBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder addSipTrunks( com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder builderForValue) { if (sipTrunksBuilder_ == null) { ensureSipTrunksIsMutable(); sipTrunks_.add(builderForValue.build()); onChanged(); } else { sipTrunksBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder addSipTrunks( int index, com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder builderForValue) { if (sipTrunksBuilder_ == null) { ensureSipTrunksIsMutable(); sipTrunks_.add(index, builderForValue.build()); onChanged(); } else { sipTrunksBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder addAllSipTrunks( java.lang.Iterable<? extends com.google.cloud.dialogflow.v2beta1.SipTrunk> values) { if (sipTrunksBuilder_ == null) { ensureSipTrunksIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, sipTrunks_); onChanged(); } else { sipTrunksBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder clearSipTrunks() { if (sipTrunksBuilder_ == null) { sipTrunks_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { sipTrunksBuilder_.clear(); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public Builder removeSipTrunks(int index) { if (sipTrunksBuilder_ == null) { ensureSipTrunksIsMutable(); sipTrunks_.remove(index); onChanged(); } else { sipTrunksBuilder_.remove(index); } return this; } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder getSipTrunksBuilder(int index) { return getSipTrunksFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.SipTrunkOrBuilder getSipTrunksOrBuilder(int index) { if (sipTrunksBuilder_ == null) { return sipTrunks_.get(index); } else { return sipTrunksBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.SipTrunkOrBuilder> getSipTrunksOrBuilderList() { if (sipTrunksBuilder_ != null) { return sipTrunksBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(sipTrunks_); } } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder addSipTrunksBuilder() { return getSipTrunksFieldBuilder() .addBuilder(com.google.cloud.dialogflow.v2beta1.SipTrunk.getDefaultInstance()); } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder addSipTrunksBuilder(int index) { return getSipTrunksFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.v2beta1.SipTrunk.getDefaultInstance()); } /** * * * <pre> * The list of SIP trunks. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.SipTrunk sip_trunks = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder> getSipTrunksBuilderList() { return getSipTrunksFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.SipTrunk, com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder, com.google.cloud.dialogflow.v2beta1.SipTrunkOrBuilder> getSipTrunksFieldBuilder() { if (sipTrunksBuilder_ == null) { sipTrunksBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.SipTrunk, com.google.cloud.dialogflow.v2beta1.SipTrunk.Builder, com.google.cloud.dialogflow.v2beta1.SipTrunkOrBuilder>( sipTrunks_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); sipTrunks_ = null; } return sipTrunksBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * more results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.ListSipTrunksResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.ListSipTrunksResponse) private static final com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse(); } public static com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListSipTrunksResponse> PARSER = new com.google.protobuf.AbstractParser<ListSipTrunksResponse>() { @java.lang.Override public ListSipTrunksResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListSipTrunksResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListSipTrunksResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListSipTrunksResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,341
java-document-ai/proto-google-cloud-document-ai-v1beta3/src/main/java/com/google/cloud/documentai/v1beta3/ListProcessorsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/documentai/v1beta3/document_processor_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.documentai.v1beta3; /** * * * <pre> * Response message for the * [ListProcessors][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors] * method. * </pre> * * Protobuf type {@code google.cloud.documentai.v1beta3.ListProcessorsResponse} */ public final class ListProcessorsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.documentai.v1beta3.ListProcessorsResponse) ListProcessorsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListProcessorsResponse.newBuilder() to construct. private ListProcessorsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListProcessorsResponse() { processors_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListProcessorsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.documentai.v1beta3.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1beta3_ListProcessorsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.documentai.v1beta3.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1beta3_ListProcessorsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.documentai.v1beta3.ListProcessorsResponse.class, com.google.cloud.documentai.v1beta3.ListProcessorsResponse.Builder.class); } public static final int PROCESSORS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.documentai.v1beta3.Processor> processors_; /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.documentai.v1beta3.Processor> getProcessorsList() { return processors_; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.documentai.v1beta3.ProcessorOrBuilder> getProcessorsOrBuilderList() { return processors_; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ @java.lang.Override public int getProcessorsCount() { return processors_.size(); } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ @java.lang.Override public com.google.cloud.documentai.v1beta3.Processor getProcessors(int index) { return processors_.get(index); } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ @java.lang.Override public com.google.cloud.documentai.v1beta3.ProcessorOrBuilder getProcessorsOrBuilder(int index) { return processors_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Points to the next processor, otherwise empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Points to the next processor, otherwise empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < processors_.size(); i++) { output.writeMessage(1, processors_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < processors_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, processors_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.documentai.v1beta3.ListProcessorsResponse)) { return super.equals(obj); } com.google.cloud.documentai.v1beta3.ListProcessorsResponse other = (com.google.cloud.documentai.v1beta3.ListProcessorsResponse) obj; if (!getProcessorsList().equals(other.getProcessorsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getProcessorsCount() > 0) { hash = (37 * hash) + PROCESSORS_FIELD_NUMBER; hash = (53 * hash) + getProcessorsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.documentai.v1beta3.ListProcessorsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for the * [ListProcessors][google.cloud.documentai.v1beta3.DocumentProcessorService.ListProcessors] * method. * </pre> * * Protobuf type {@code google.cloud.documentai.v1beta3.ListProcessorsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.documentai.v1beta3.ListProcessorsResponse) com.google.cloud.documentai.v1beta3.ListProcessorsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.documentai.v1beta3.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1beta3_ListProcessorsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.documentai.v1beta3.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1beta3_ListProcessorsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.documentai.v1beta3.ListProcessorsResponse.class, com.google.cloud.documentai.v1beta3.ListProcessorsResponse.Builder.class); } // Construct using com.google.cloud.documentai.v1beta3.ListProcessorsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (processorsBuilder_ == null) { processors_ = java.util.Collections.emptyList(); } else { processors_ = null; processorsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.documentai.v1beta3.DocumentAiProcessorService .internal_static_google_cloud_documentai_v1beta3_ListProcessorsResponse_descriptor; } @java.lang.Override public com.google.cloud.documentai.v1beta3.ListProcessorsResponse getDefaultInstanceForType() { return com.google.cloud.documentai.v1beta3.ListProcessorsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.documentai.v1beta3.ListProcessorsResponse build() { com.google.cloud.documentai.v1beta3.ListProcessorsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.documentai.v1beta3.ListProcessorsResponse buildPartial() { com.google.cloud.documentai.v1beta3.ListProcessorsResponse result = new com.google.cloud.documentai.v1beta3.ListProcessorsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.documentai.v1beta3.ListProcessorsResponse result) { if (processorsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { processors_ = java.util.Collections.unmodifiableList(processors_); bitField0_ = (bitField0_ & ~0x00000001); } result.processors_ = processors_; } else { result.processors_ = processorsBuilder_.build(); } } private void buildPartial0(com.google.cloud.documentai.v1beta3.ListProcessorsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.documentai.v1beta3.ListProcessorsResponse) { return mergeFrom((com.google.cloud.documentai.v1beta3.ListProcessorsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.documentai.v1beta3.ListProcessorsResponse other) { if (other == com.google.cloud.documentai.v1beta3.ListProcessorsResponse.getDefaultInstance()) return this; if (processorsBuilder_ == null) { if (!other.processors_.isEmpty()) { if (processors_.isEmpty()) { processors_ = other.processors_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureProcessorsIsMutable(); processors_.addAll(other.processors_); } onChanged(); } } else { if (!other.processors_.isEmpty()) { if (processorsBuilder_.isEmpty()) { processorsBuilder_.dispose(); processorsBuilder_ = null; processors_ = other.processors_; bitField0_ = (bitField0_ & ~0x00000001); processorsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getProcessorsFieldBuilder() : null; } else { processorsBuilder_.addAllMessages(other.processors_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.documentai.v1beta3.Processor m = input.readMessage( com.google.cloud.documentai.v1beta3.Processor.parser(), extensionRegistry); if (processorsBuilder_ == null) { ensureProcessorsIsMutable(); processors_.add(m); } else { processorsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.documentai.v1beta3.Processor> processors_ = java.util.Collections.emptyList(); private void ensureProcessorsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { processors_ = new java.util.ArrayList<com.google.cloud.documentai.v1beta3.Processor>(processors_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.documentai.v1beta3.Processor, com.google.cloud.documentai.v1beta3.Processor.Builder, com.google.cloud.documentai.v1beta3.ProcessorOrBuilder> processorsBuilder_; /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public java.util.List<com.google.cloud.documentai.v1beta3.Processor> getProcessorsList() { if (processorsBuilder_ == null) { return java.util.Collections.unmodifiableList(processors_); } else { return processorsBuilder_.getMessageList(); } } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public int getProcessorsCount() { if (processorsBuilder_ == null) { return processors_.size(); } else { return processorsBuilder_.getCount(); } } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public com.google.cloud.documentai.v1beta3.Processor getProcessors(int index) { if (processorsBuilder_ == null) { return processors_.get(index); } else { return processorsBuilder_.getMessage(index); } } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder setProcessors(int index, com.google.cloud.documentai.v1beta3.Processor value) { if (processorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProcessorsIsMutable(); processors_.set(index, value); onChanged(); } else { processorsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder setProcessors( int index, com.google.cloud.documentai.v1beta3.Processor.Builder builderForValue) { if (processorsBuilder_ == null) { ensureProcessorsIsMutable(); processors_.set(index, builderForValue.build()); onChanged(); } else { processorsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder addProcessors(com.google.cloud.documentai.v1beta3.Processor value) { if (processorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProcessorsIsMutable(); processors_.add(value); onChanged(); } else { processorsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder addProcessors(int index, com.google.cloud.documentai.v1beta3.Processor value) { if (processorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProcessorsIsMutable(); processors_.add(index, value); onChanged(); } else { processorsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder addProcessors( com.google.cloud.documentai.v1beta3.Processor.Builder builderForValue) { if (processorsBuilder_ == null) { ensureProcessorsIsMutable(); processors_.add(builderForValue.build()); onChanged(); } else { processorsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder addProcessors( int index, com.google.cloud.documentai.v1beta3.Processor.Builder builderForValue) { if (processorsBuilder_ == null) { ensureProcessorsIsMutable(); processors_.add(index, builderForValue.build()); onChanged(); } else { processorsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder addAllProcessors( java.lang.Iterable<? extends com.google.cloud.documentai.v1beta3.Processor> values) { if (processorsBuilder_ == null) { ensureProcessorsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, processors_); onChanged(); } else { processorsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder clearProcessors() { if (processorsBuilder_ == null) { processors_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { processorsBuilder_.clear(); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public Builder removeProcessors(int index) { if (processorsBuilder_ == null) { ensureProcessorsIsMutable(); processors_.remove(index); onChanged(); } else { processorsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public com.google.cloud.documentai.v1beta3.Processor.Builder getProcessorsBuilder(int index) { return getProcessorsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public com.google.cloud.documentai.v1beta3.ProcessorOrBuilder getProcessorsOrBuilder( int index) { if (processorsBuilder_ == null) { return processors_.get(index); } else { return processorsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public java.util.List<? extends com.google.cloud.documentai.v1beta3.ProcessorOrBuilder> getProcessorsOrBuilderList() { if (processorsBuilder_ != null) { return processorsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(processors_); } } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public com.google.cloud.documentai.v1beta3.Processor.Builder addProcessorsBuilder() { return getProcessorsFieldBuilder() .addBuilder(com.google.cloud.documentai.v1beta3.Processor.getDefaultInstance()); } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public com.google.cloud.documentai.v1beta3.Processor.Builder addProcessorsBuilder(int index) { return getProcessorsFieldBuilder() .addBuilder(index, com.google.cloud.documentai.v1beta3.Processor.getDefaultInstance()); } /** * * * <pre> * The list of processors. * </pre> * * <code>repeated .google.cloud.documentai.v1beta3.Processor processors = 1;</code> */ public java.util.List<com.google.cloud.documentai.v1beta3.Processor.Builder> getProcessorsBuilderList() { return getProcessorsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.documentai.v1beta3.Processor, com.google.cloud.documentai.v1beta3.Processor.Builder, com.google.cloud.documentai.v1beta3.ProcessorOrBuilder> getProcessorsFieldBuilder() { if (processorsBuilder_ == null) { processorsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.documentai.v1beta3.Processor, com.google.cloud.documentai.v1beta3.Processor.Builder, com.google.cloud.documentai.v1beta3.ProcessorOrBuilder>( processors_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); processors_ = null; } return processorsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Points to the next processor, otherwise empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Points to the next processor, otherwise empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Points to the next processor, otherwise empty. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Points to the next processor, otherwise empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Points to the next processor, otherwise empty. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.documentai.v1beta3.ListProcessorsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.documentai.v1beta3.ListProcessorsResponse) private static final com.google.cloud.documentai.v1beta3.ListProcessorsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.documentai.v1beta3.ListProcessorsResponse(); } public static com.google.cloud.documentai.v1beta3.ListProcessorsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListProcessorsResponse> PARSER = new com.google.protobuf.AbstractParser<ListProcessorsResponse>() { @java.lang.Override public ListProcessorsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListProcessorsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListProcessorsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.documentai.v1beta3.ListProcessorsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,444
java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/CreateSKAdNetworkConversionValueSchemaRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/analytics/admin/v1alpha/analytics_admin.proto // Protobuf Java Version: 3.25.8 package com.google.analytics.admin.v1alpha; /** * * * <pre> * Request message for CreateSKAdNetworkConversionValueSchema RPC. * </pre> * * Protobuf type {@code * google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest} */ public final class CreateSKAdNetworkConversionValueSchemaRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest) CreateSKAdNetworkConversionValueSchemaRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateSKAdNetworkConversionValueSchemaRequest.newBuilder() to construct. private CreateSKAdNetworkConversionValueSchemaRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateSKAdNetworkConversionValueSchemaRequest() { parent_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateSKAdNetworkConversionValueSchemaRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_CreateSKAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_CreateSKAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest.class, com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest.Builder .class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource where this schema will be created. * Format: properties/{property}/dataStreams/{dataStream} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource where this schema will be created. * Format: properties/{property}/dataStreams/{dataStream} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SKADNETWORK_CONVERSION_VALUE_SCHEMA_FIELD_NUMBER = 2; private com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetworkConversionValueSchema_; /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the skadnetworkConversionValueSchema field is set. */ @java.lang.Override public boolean hasSkadnetworkConversionValueSchema() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The skadnetworkConversionValueSchema. */ @java.lang.Override public com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema getSkadnetworkConversionValueSchema() { return skadnetworkConversionValueSchema_ == null ? com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema.getDefaultInstance() : skadnetworkConversionValueSchema_; } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchemaOrBuilder getSkadnetworkConversionValueSchemaOrBuilder() { return skadnetworkConversionValueSchema_ == null ? com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema.getDefaultInstance() : skadnetworkConversionValueSchema_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getSkadnetworkConversionValueSchema()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, getSkadnetworkConversionValueSchema()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest)) { return super.equals(obj); } com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest other = (com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasSkadnetworkConversionValueSchema() != other.hasSkadnetworkConversionValueSchema()) return false; if (hasSkadnetworkConversionValueSchema()) { if (!getSkadnetworkConversionValueSchema() .equals(other.getSkadnetworkConversionValueSchema())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (hasSkadnetworkConversionValueSchema()) { hash = (37 * hash) + SKADNETWORK_CONVERSION_VALUE_SCHEMA_FIELD_NUMBER; hash = (53 * hash) + getSkadnetworkConversionValueSchema().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for CreateSKAdNetworkConversionValueSchema RPC. * </pre> * * Protobuf type {@code * google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest) com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_CreateSKAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_CreateSKAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest .class, com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest .Builder.class); } // Construct using // com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getSkadnetworkConversionValueSchemaFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; skadnetworkConversionValueSchema_ = null; if (skadnetworkConversionValueSchemaBuilder_ != null) { skadnetworkConversionValueSchemaBuilder_.dispose(); skadnetworkConversionValueSchemaBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_CreateSKAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override public com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest .getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest build() { com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest buildPartial() { com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest result = new com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest( this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.skadnetworkConversionValueSchema_ = skadnetworkConversionValueSchemaBuilder_ == null ? skadnetworkConversionValueSchema_ : skadnetworkConversionValueSchemaBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest) { return mergeFrom( (com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest other) { if (other == com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest .getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasSkadnetworkConversionValueSchema()) { mergeSkadnetworkConversionValueSchema(other.getSkadnetworkConversionValueSchema()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( getSkadnetworkConversionValueSchemaFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource where this schema will be created. * Format: properties/{property}/dataStreams/{dataStream} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource where this schema will be created. * Format: properties/{property}/dataStreams/{dataStream} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource where this schema will be created. * Format: properties/{property}/dataStreams/{dataStream} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource where this schema will be created. * Format: properties/{property}/dataStreams/{dataStream} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource where this schema will be created. * Format: properties/{property}/dataStreams/{dataStream} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetworkConversionValueSchema_; private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema, com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema.Builder, com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchemaOrBuilder> skadnetworkConversionValueSchemaBuilder_; /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the skadnetworkConversionValueSchema field is set. */ public boolean hasSkadnetworkConversionValueSchema() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The skadnetworkConversionValueSchema. */ public com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema getSkadnetworkConversionValueSchema() { if (skadnetworkConversionValueSchemaBuilder_ == null) { return skadnetworkConversionValueSchema_ == null ? com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema .getDefaultInstance() : skadnetworkConversionValueSchema_; } else { return skadnetworkConversionValueSchemaBuilder_.getMessage(); } } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSkadnetworkConversionValueSchema( com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema value) { if (skadnetworkConversionValueSchemaBuilder_ == null) { if (value == null) { throw new NullPointerException(); } skadnetworkConversionValueSchema_ = value; } else { skadnetworkConversionValueSchemaBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSkadnetworkConversionValueSchema( com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema.Builder builderForValue) { if (skadnetworkConversionValueSchemaBuilder_ == null) { skadnetworkConversionValueSchema_ = builderForValue.build(); } else { skadnetworkConversionValueSchemaBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeSkadnetworkConversionValueSchema( com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema value) { if (skadnetworkConversionValueSchemaBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && skadnetworkConversionValueSchema_ != null && skadnetworkConversionValueSchema_ != com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema .getDefaultInstance()) { getSkadnetworkConversionValueSchemaBuilder().mergeFrom(value); } else { skadnetworkConversionValueSchema_ = value; } } else { skadnetworkConversionValueSchemaBuilder_.mergeFrom(value); } if (skadnetworkConversionValueSchema_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearSkadnetworkConversionValueSchema() { bitField0_ = (bitField0_ & ~0x00000002); skadnetworkConversionValueSchema_ = null; if (skadnetworkConversionValueSchemaBuilder_ != null) { skadnetworkConversionValueSchemaBuilder_.dispose(); skadnetworkConversionValueSchemaBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema.Builder getSkadnetworkConversionValueSchemaBuilder() { bitField0_ |= 0x00000002; onChanged(); return getSkadnetworkConversionValueSchemaFieldBuilder().getBuilder(); } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchemaOrBuilder getSkadnetworkConversionValueSchemaOrBuilder() { if (skadnetworkConversionValueSchemaBuilder_ != null) { return skadnetworkConversionValueSchemaBuilder_.getMessageOrBuilder(); } else { return skadnetworkConversionValueSchema_ == null ? com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema .getDefaultInstance() : skadnetworkConversionValueSchema_; } } /** * * * <pre> * Required. SKAdNetwork conversion value schema to create. * </pre> * * <code> * .google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema skadnetwork_conversion_value_schema = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema, com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema.Builder, com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchemaOrBuilder> getSkadnetworkConversionValueSchemaFieldBuilder() { if (skadnetworkConversionValueSchemaBuilder_ == null) { skadnetworkConversionValueSchemaBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema, com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema.Builder, com.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchemaOrBuilder>( getSkadnetworkConversionValueSchema(), getParentForChildren(), isClean()); skadnetworkConversionValueSchema_ = null; } return skadnetworkConversionValueSchemaBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest) private static final com.google.analytics.admin.v1alpha .CreateSKAdNetworkConversionValueSchemaRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest(); } public static com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateSKAdNetworkConversionValueSchemaRequest> PARSER = new com.google.protobuf.AbstractParser<CreateSKAdNetworkConversionValueSchemaRequest>() { @java.lang.Override public CreateSKAdNetworkConversionValueSchemaRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException() .setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<CreateSKAdNetworkConversionValueSchemaRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateSKAdNetworkConversionValueSchemaRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/geode
36,674
geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/GatewayReceiverCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.tier.sockets.command; import static java.lang.String.format; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.NotNull; import org.apache.geode.CancelException; import org.apache.geode.annotations.Immutable; import org.apache.geode.cache.EntryNotFoundException; import org.apache.geode.cache.RegionDestroyedException; import org.apache.geode.cache.operations.DestroyOperationContext; import org.apache.geode.cache.operations.PutOperationContext; import org.apache.geode.cache.wan.GatewayReceiver; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.distributed.internal.DistributionStats; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.cache.EntryEventImpl; import org.apache.geode.internal.cache.EventID; import org.apache.geode.internal.cache.EventIDHolder; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.LocalRegion; import org.apache.geode.internal.cache.tier.CachedRegionHelper; import org.apache.geode.internal.cache.tier.Command; import org.apache.geode.internal.cache.tier.MessageType; import org.apache.geode.internal.cache.tier.sockets.BaseCommand; import org.apache.geode.internal.cache.tier.sockets.Message; import org.apache.geode.internal.cache.tier.sockets.Part; import org.apache.geode.internal.cache.tier.sockets.ServerConnection; import org.apache.geode.internal.cache.versions.VersionTag; import org.apache.geode.internal.cache.wan.BatchException70; import org.apache.geode.internal.cache.wan.GatewayReceiverStats; import org.apache.geode.internal.cache.wan.GatewaySenderEventImpl; import org.apache.geode.internal.security.AuthorizeRequest; import org.apache.geode.internal.security.SecurityService; import org.apache.geode.internal.util.BlobHelper; import org.apache.geode.pdx.PdxRegistryMismatchException; import org.apache.geode.pdx.internal.EnumId; import org.apache.geode.pdx.internal.EnumInfo; import org.apache.geode.pdx.internal.PdxType; import org.apache.geode.pdx.internal.PeerTypeRegistration; public class GatewayReceiverCommand extends BaseCommand { @Immutable private static final GatewayReceiverCommand SINGLETON = new GatewayReceiverCommand(); public static Command getCommand() { return SINGLETON; } private GatewayReceiverCommand() { // nothing } private void handleRegionNull(ServerConnection servConn, String regionName, int batchId) { InternalCache cache = servConn.getCachedRegionHelper().getCacheForGatewayCommand(); if (cache != null && cache.isCacheAtShutdownAll()) { throw cache.getCacheClosedException("Shutdown occurred during message processing"); } String reason = format("Region %s was not found during batch create request %s", regionName, batchId); throw new RegionDestroyedException(reason, regionName); } @Override public void cmdExecute(final @NotNull Message clientMessage, final @NotNull ServerConnection serverConnection, final @NotNull SecurityService securityService, long start) throws IOException, InterruptedException { CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper(); GatewayReceiverStats stats = (GatewayReceiverStats) serverConnection.getCacheServerStats(); { long oldStart = start; start = DistributionStats.getStatTime(); stats.incReadProcessBatchRequestTime(start - oldStart); } stats.incBatchSize(clientMessage.getPayloadLength()); // Retrieve the number of events Part numberOfEventsPart = clientMessage.getPart(0); int numberOfEvents = numberOfEventsPart.getInt(); stats.incEventsReceived(numberOfEvents); // Retrieve the batch id Part batchIdPart = clientMessage.getPart(1); int batchId = batchIdPart.getInt(); // If this batch has already been seen, do not reply. // Instead, drop the batch and continue. if (batchId <= serverConnection.getLatestBatchIdReplied()) { if (GatewayReceiver.APPLY_RETRIES) { // Do nothing!!! logger.warn( "Received process batch request {} that has already been or is being processed. gemfire.gateway.ApplyRetries is set, so this batch will be processed anyway.", batchId); } else { logger.warn( "Received process batch request {} that has already been or is being processed. This process batch request is being ignored.", batchId); writeReply(clientMessage, serverConnection, batchId, numberOfEvents); return; } stats.incDuplicateBatchesReceived(); } // Verify the batches arrive in order if (batchId != serverConnection.getLatestBatchIdReplied() + 1) { logger.warn( "Received process batch request {} out of order. The id of the last batch processed was {}. This batch request will be processed, but some messages may have been lost.", batchId, serverConnection.getLatestBatchIdReplied()); stats.incOutoforderBatchesReceived(); } if (logger.isDebugEnabled()) { logger.debug("Received process batch request {} that will be processed.", batchId); } if (logger.isDebugEnabled()) { logger.debug( "{}: Received process batch request {} containing {} events ({} bytes) with {} acknowledgement on {}", serverConnection.getName(), batchId, numberOfEvents, clientMessage.getPayloadLength(), "normal", serverConnection.getSocketString()); } // Retrieve the events from the message parts. The '2' below // represents the number of events (part0) and the batchId (part1) int partNumber = 2; int dsid = clientMessage.getPart(partNumber++).getInt(); boolean removeOnException = clientMessage.getPart(partNumber++).getSerializedForm()[0] == 1; // event received in batch also have PDX events at the start of the batch,to // represent correct index on which the exception occurred, number of PDX // events need to be subtracted. int indexWithoutPDXEvent = -1; // Part valuePart = null; Throwable fatalException = null; List<BatchException70> exceptions = new ArrayList<>(); for (int i = 0; i < numberOfEvents; i++) { indexWithoutPDXEvent++; Part actionTypePart = clientMessage.getPart(partNumber); int actionType = actionTypePart.getInt(); boolean callbackArgExists = false; try { boolean isPdxEvent = false; boolean retry = true; do { if (isPdxEvent) { // This is a retried event. Reset the PDX event index. indexWithoutPDXEvent++; } isPdxEvent = false; Part possibleDuplicatePart = clientMessage.getPart(partNumber + 1); byte[] possibleDuplicatePartBytes; try { possibleDuplicatePartBytes = (byte[]) possibleDuplicatePart.getObject(); } catch (Exception e) { logger.warn(format( "%s: Caught exception processing batch request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); handleException(removeOnException, stats, e); break; } boolean possibleDuplicate = possibleDuplicatePartBytes[0] == 0x01; if (possibleDuplicate) { stats.incPossibleDuplicateEventsReceived(); } // Retrieve the region name from the message parts Part regionNamePart = clientMessage.getPart(partNumber + 2); String regionName = regionNamePart.getCachedString(); if (regionName.equals(PeerTypeRegistration.REGION_FULL_PATH)) { indexWithoutPDXEvent--; isPdxEvent = true; } // Retrieve the event id from the message parts // This was going to be used to determine possible // duplication of events, but it is unused now. In // fact the event id is overridden by the FROM_GATEWAY // token. Part eventIdPart = clientMessage.getPart(partNumber + 3); eventIdPart.setVersion(serverConnection.getClientVersion()); // String eventId = eventIdPart.getString(); EventID eventId; try { eventId = (EventID) eventIdPart.getObject(); } catch (Exception e) { logger.warn(format( "%s: Caught exception processing batch request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); handleException(removeOnException, stats, e); break; } // Retrieve the key from the message parts Part keyPart = clientMessage.getPart(partNumber + 4); Object key; try { key = keyPart.getStringOrObject(); } catch (Exception e) { logger.warn(format( "%s: Caught exception processing batch request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); handleException(removeOnException, stats, e); break; } int index; Part callbackArgPart; EventIDHolder clientEvent; long versionTimeStamp; Part callbackArgExistsPart; LocalRegion region; Object callbackArg = null; switch (actionType) { case 0: // Create try { // Retrieve the value from the message parts (do not deserialize it) valuePart = clientMessage.getPart(partNumber + 5); // Retrieve the callbackArg from the message parts if necessary index = partNumber + 6; callbackArgExistsPart = clientMessage.getPart(index++); { byte[] partBytes = (byte[]) callbackArgExistsPart.getObject(); callbackArgExists = partBytes[0] == 0x01; } if (callbackArgExists) { callbackArgPart = clientMessage.getPart(index++); try { callbackArg = callbackArgPart.getObject(); } catch (Exception e) { logger .warn(format( "%s: Caught exception processing batch create request %s for %s events", serverConnection.getName(), batchId, numberOfEvents), e); throw e; } } if (logger.isDebugEnabled()) { logger.debug( "{}: Processing batch create request {} on {} for region {} key {} value {} callbackArg {}, eventId={}", serverConnection.getName(), batchId, serverConnection.getSocketString(), regionName, key, valuePart, callbackArg, eventId); } versionTimeStamp = clientMessage.getPart(index++).getLong(); // Process the create request if (key == null || regionName == null) { String message = null; if (key == null) { message = "%s: The input key for the batch create request %s is null"; } if (regionName == null) { message = "%s: The input region name for the batch create request %s is null"; } String s = format(message, serverConnection.getName(), batchId); logger.warn(s); throw new Exception(s); } region = (LocalRegion) crHelper.getCacheForGatewayCommand().getRegion(regionName); if (region == null) { handleRegionNull(serverConnection, regionName, batchId); } else { clientEvent = new EventIDHolder(eventId); if (versionTimeStamp > 0) { VersionTag tag = VersionTag.create(region.getVersionMember()); tag.setIsGatewayTag(true); tag.setVersionTimeStamp(versionTimeStamp); tag.setDistributedSystemId(dsid); clientEvent.setVersionTag(tag); } clientEvent.setPossibleDuplicate(possibleDuplicate); handleMessageRetry(region, clientEvent); byte[] value = valuePart.getSerializedForm(); boolean isObject = valuePart.isObject(); // This should be done on client while sending since that is the WAN gateway AuthorizeRequest authzRequest = serverConnection.getAuthzRequest(); if (authzRequest != null) { PutOperationContext putContext = authzRequest.putAuthorize(regionName, key, value, isObject, callbackArg); value = putContext.getSerializedValue(); isObject = putContext.isObject(); } // Attempt to create the entry boolean result; if (isPdxEvent) { result = addPdxType(crHelper, key, value); } else { result = region.basicBridgeCreate(key, value, isObject, callbackArg, serverConnection.getProxyID(), false, clientEvent, false); // If the create fails (presumably because it already exists), // attempt to update the entry if (!result) { result = region.basicBridgePut(key, value, null, isObject, callbackArg, serverConnection.getProxyID(), clientEvent, true); } } if (result || clientEvent.isConcurrencyConflict()) { serverConnection.setModificationInfo(true, regionName, key); stats.incCreateRequest(); retry = false; } else { // This exception will be logged in the catch block below throw new Exception( format( "%s: Failed to create or update entry for region %s key %s value %s callbackArg %s", serverConnection.getName(), regionName, key, valuePart, callbackArg)); } } } catch (Exception e) { logger.warn(format( "%s: Caught exception processing batch create request %s for %s events", serverConnection.getName(), batchId, numberOfEvents), e); handleException(removeOnException, stats, e); } break; case 1: // Update case GatewaySenderEventImpl.UPDATE_ACTION_NO_GENERATE_CALLBACKS: try { // Retrieve the value from the message parts (do not deserialize it) valuePart = clientMessage.getPart(partNumber + 5); // Retrieve the callbackArg from the message parts if necessary index = partNumber + 6; callbackArgExistsPart = clientMessage.getPart(index++); { byte[] partBytes = (byte[]) callbackArgExistsPart.getObject(); callbackArgExists = partBytes[0] == 0x01; } if (callbackArgExists) { callbackArgPart = clientMessage.getPart(index++); try { callbackArg = callbackArgPart.getObject(); } catch (Exception e) { logger .warn( format( "%s: Caught exception processing batch update request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); throw e; } } versionTimeStamp = clientMessage.getPart(index++).getLong(); if (logger.isDebugEnabled()) { logger.debug( "{}: Processing batch update request {} on {} for region {} key {} value {} callbackArg {}", serverConnection.getName(), batchId, serverConnection.getSocketString(), regionName, key, valuePart, callbackArg); } // Process the update request if (key == null || regionName == null) { String message = null; if (key == null) { message = "%s: The input key for the batch update request %s is null"; } if (regionName == null) { message = "%s: The input region name for the batch update request %s is null"; } String s = format(message, serverConnection.getName(), batchId); logger.warn(s); throw new Exception(s); } region = (LocalRegion) crHelper.getCacheForGatewayCommand().getRegion(regionName); if (region == null) { handleRegionNull(serverConnection, regionName, batchId); } else { clientEvent = new EventIDHolder(eventId); if (versionTimeStamp > 0) { VersionTag tag = VersionTag.create(region.getVersionMember()); tag.setIsGatewayTag(true); tag.setVersionTimeStamp(versionTimeStamp); tag.setDistributedSystemId(dsid); clientEvent.setVersionTag(tag); } clientEvent.setPossibleDuplicate(possibleDuplicate); handleMessageRetry(region, clientEvent); byte[] value = valuePart.getSerializedForm(); boolean isObject = valuePart.isObject(); AuthorizeRequest authzRequest = serverConnection.getAuthzRequest(); if (authzRequest != null) { PutOperationContext putContext = authzRequest.putAuthorize(regionName, key, value, isObject, callbackArg, PutOperationContext.UPDATE); value = putContext.getSerializedValue(); isObject = putContext.isObject(); } final boolean result; if (isPdxEvent) { result = addPdxType(crHelper, key, value); } else { boolean generateCallbacks = actionType != GatewaySenderEventImpl.UPDATE_ACTION_NO_GENERATE_CALLBACKS; result = region.basicBridgePut(key, value, null, isObject, callbackArg, serverConnection.getProxyID(), clientEvent, generateCallbacks); } if (result || clientEvent.isConcurrencyConflict()) { serverConnection.setModificationInfo(true, regionName, key); stats.incUpdateRequest(); retry = false; } else { final String message = "%s: Failed to update entry for region %s, key %s, value %s, and callbackArg %s"; String s = format(message, serverConnection.getName(), regionName, key, valuePart, callbackArg); logger.info(s); throw new Exception(s); } } } catch (Exception e) { // Preserve the connection under all circumstances logger.warn(format( "%s: Caught exception processing batch update request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); handleException(removeOnException, stats, e); } break; case 2: // Destroy try { // Retrieve the callbackArg from the message parts if necessary index = partNumber + 5; callbackArgExistsPart = clientMessage.getPart(index++); { byte[] partBytes = (byte[]) callbackArgExistsPart.getObject(); callbackArgExists = partBytes[0] == 0x01; } if (callbackArgExists) { callbackArgPart = clientMessage.getPart(index++); try { callbackArg = callbackArgPart.getObject(); } catch (Exception e) { logger .warn( format( "%s: Caught exception processing batch destroy request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); throw e; } } versionTimeStamp = clientMessage.getPart(index++).getLong(); if (logger.isDebugEnabled()) { logger.debug("{}: Processing batch destroy request {} on {} for region {} key {}", serverConnection.getName(), batchId, serverConnection.getSocketString(), regionName, key); } // Process the destroy request if (key == null || regionName == null) { String message = null; if (key == null) { message = "%s: The input key for the batch destroy request %s is null"; } if (regionName == null) { message = "%s: The input region name for the batch destroy request %s is null"; } String s = format(message, serverConnection.getName(), batchId); logger.warn(s); throw new Exception(s); } region = (LocalRegion) crHelper.getCacheForGatewayCommand().getRegion(regionName); if (region == null) { handleRegionNull(serverConnection, regionName, batchId); } else { clientEvent = new EventIDHolder(eventId); if (versionTimeStamp > 0) { VersionTag tag = VersionTag.create(region.getVersionMember()); tag.setIsGatewayTag(true); tag.setVersionTimeStamp(versionTimeStamp); tag.setDistributedSystemId(dsid); clientEvent.setVersionTag(tag); } handleMessageRetry(region, clientEvent); // Destroy the entry AuthorizeRequest authzRequest = serverConnection.getAuthzRequest(); if (authzRequest != null) { DestroyOperationContext destroyContext = authzRequest.destroyAuthorize(regionName, key, callbackArg); callbackArg = destroyContext.getCallbackArg(); } try { region.basicBridgeDestroy(key, callbackArg, serverConnection.getProxyID(), false, clientEvent); serverConnection.setModificationInfo(true, regionName, key); } catch (EntryNotFoundException e) { logger.info("{}: during batch destroy no entry was found for key {}", serverConnection.getName(), key); } stats.incDestroyRequest(); retry = false; } } catch (Exception e) { logger.warn(format( "%s: Caught exception processing batch destroy request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); handleException(removeOnException, stats, e); } break; case 3: // Update Time-stamp for a RegionEntry try { // Region name regionNamePart = clientMessage.getPart(partNumber + 2); regionName = regionNamePart.getCachedString(); // Retrieve the event id from the message parts eventIdPart = clientMessage.getPart(partNumber + 3); eventId = (EventID) eventIdPart.getObject(); // Retrieve the key from the message parts keyPart = clientMessage.getPart(partNumber + 4); key = keyPart.getStringOrObject(); // Retrieve the callbackArg from the message parts if necessary index = partNumber + 5; callbackArgExistsPart = clientMessage.getPart(index++); byte[] partBytes = (byte[]) callbackArgExistsPart.getObject(); callbackArgExists = partBytes[0] == 0x01; if (callbackArgExists) { callbackArgPart = clientMessage.getPart(index++); callbackArg = callbackArgPart.getObject(); } versionTimeStamp = clientMessage.getPart(index++).getLong(); if (logger.isDebugEnabled()) { logger.debug( "{}: Processing batch update-version request {} on {} for region {} key {} value {} callbackArg {}", serverConnection.getName(), batchId, serverConnection.getSocketString(), regionName, key, valuePart, callbackArg); } // Process the update time-stamp request if (key == null || regionName == null) { String message = "%s: Caught exception processing batch update version request request %s containing %s events"; String s = format(message, serverConnection.getName(), batchId, numberOfEvents); logger.warn(s); throw new Exception(s); } else { region = (LocalRegion) crHelper.getCacheForGatewayCommand().getRegion(regionName); if (region == null) { handleRegionNull(serverConnection, regionName, batchId); } else { clientEvent = new EventIDHolder(eventId); if (versionTimeStamp > 0) { VersionTag tag = VersionTag.create(region.getVersionMember()); tag.setIsGatewayTag(true); tag.setVersionTimeStamp(versionTimeStamp); tag.setDistributedSystemId(dsid); clientEvent.setVersionTag(tag); } // Update the version tag try { region.basicBridgeUpdateVersionStamp(key, callbackArg, serverConnection.getProxyID(), false, clientEvent); } catch (EntryNotFoundException e) { logger.info( "Entry for key {} was not found in Region {} during ProcessBatch for Update Entry Version", serverConnection.getName(), key); } retry = false; } } } catch (Exception e) { logger.warn(format( "%s: Caught exception processing batch update version request request %s containing %s events", serverConnection.getName(), batchId, numberOfEvents), e); handleException(removeOnException, stats, e); } break; default: logger.fatal("{}: Unknown action type ({}) for batch from {}", serverConnection.getName(), actionType, serverConnection.getSocketString()); stats.incUnknowsOperationsReceived(); } } while (retry); } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug( "{} ignoring message of type {} from client {} because shutdown occurred during message processing.", serverConnection.getName(), clientMessage.getMessageType(), serverConnection.getProxyID()); } serverConnection.setFlagProcessMessagesAsFalse(); serverConnection.setClientDisconnectedException(e); return; } catch (Exception e) { // If an interrupted exception is thrown , rethrow it checkForInterrupt(serverConnection, e); // If we have an issue with the PDX registry, stop processing more data if (e.getCause() instanceof PdxRegistryMismatchException) { fatalException = e.getCause(); logger.fatal(format( "This gateway receiver has received a PDX type from %s that does match the existing PDX type. This gateway receiver will not process any more events, in order to prevent receiving objects which may not be deserializable.", serverConnection.getMembershipID()), e.getCause()); break; } // Increment the batch id unless the received batch id is -1 (a // failover batch) DistributedSystem ds = crHelper.getCacheForGatewayCommand().getDistributedSystem(); String exceptionMessage = format( "Exception occurred while processing a batch on the receiver running on DistributedSystem with Id: %s, DistributedMember on which the receiver is running: %s", ((InternalDistributedSystem) ds).getDistributionManager().getDistributedSystemId(), ds.getDistributedMember()); BatchException70 be = new BatchException70(exceptionMessage, e, indexWithoutPDXEvent, batchId); exceptions.add(be); } finally { // Increment the partNumber if (actionType == 0 /* create */ || actionType == 1 /* update */ || actionType == GatewaySenderEventImpl.UPDATE_ACTION_NO_GENERATE_CALLBACKS) { if (callbackArgExists) { partNumber += 9; } else { partNumber += 8; } } else if (actionType == 2 /* destroy */) { if (callbackArgExists) { partNumber += 8; } else { partNumber += 7; } } else if (actionType == 3 /* update-version */) { if (callbackArgExists) { partNumber += 8; } else { partNumber += 7; } } } } { long oldStart = start; start = DistributionStats.getStatTime(); stats.incProcessBatchTime(start - oldStart); } if (fatalException != null) { serverConnection.incrementLatestBatchIdReplied(batchId); writeFatalException(clientMessage, fatalException, serverConnection); serverConnection.setAsTrue(RESPONDED); } else if (!exceptions.isEmpty()) { serverConnection.incrementLatestBatchIdReplied(batchId); writeBatchException(clientMessage, exceptions, serverConnection); serverConnection.setAsTrue(RESPONDED); } else { // Increment the batch id unless the received batch id is -1 (a failover // batch) serverConnection.incrementLatestBatchIdReplied(batchId); writeReply(clientMessage, serverConnection, batchId, numberOfEvents); serverConnection.setAsTrue(RESPONDED); stats.incWriteProcessBatchResponseTime(DistributionStats.getStatTime() - start); if (logger.isDebugEnabled()) { logger.debug( "{}: Sent process batch normal response for batch {} containing {} events ({} bytes) with {} acknowledgement on {}", serverConnection.getName(), batchId, numberOfEvents, clientMessage.getPayloadLength(), "normal", serverConnection.getSocketString()); } } } private boolean addPdxType(CachedRegionHelper crHelper, Object key, Object value) throws Exception { if (key instanceof EnumId) { EnumId enumId = (EnumId) key; value = BlobHelper.deserializeBlob((byte[]) value); crHelper.getCacheForGatewayCommand().getPdxRegistry().addRemoteEnum(enumId.intValue(), (EnumInfo) value); } else { value = BlobHelper.deserializeBlob((byte[]) value); crHelper.getCacheForGatewayCommand().getPdxRegistry().addRemoteType((int) key, (PdxType) value); } return true; } private void handleException(boolean removeOnException, GatewayReceiverStats stats, Exception e) throws Exception { if (e instanceof CancelException) { throw e; } if (shouldThrowException(removeOnException)) { throw e; } else { stats.incEventsRetried(); Thread.sleep(500); } } private boolean shouldThrowException(boolean removeOnException) { // Split out in case specific exceptions would short-circuit retry logic. // Currently, it just considers the boolean. return removeOnException; } private void handleMessageRetry(LocalRegion region, EntryEventImpl clientEvent) { if (clientEvent.isPossibleDuplicate()) { if (region.getAttributes().getConcurrencyChecksEnabled()) { // recover the version tag from other servers clientEvent.setRegion(region); if (!recoverVersionTagForRetriedOperation(clientEvent)) { // no-one has seen this event clientEvent.setPossibleDuplicate(false); } } } } private void writeReply(Message msg, ServerConnection servConn, int batchId, int numberOfEvents) throws IOException { Message replyMsg = servConn.getResponseMessage(); replyMsg.setMessageType(MessageType.REPLY); replyMsg.setTransactionId(msg.getTransactionId()); replyMsg.setNumberOfParts(2); replyMsg.addIntPart(batchId); replyMsg.addIntPart(numberOfEvents); replyMsg.setTransactionId(msg.getTransactionId()); replyMsg.send(servConn); servConn.setAsTrue(Command.RESPONDED); if (logger.isDebugEnabled()) { logger.debug("{}: rpl tx: {} batchId {} numberOfEvents: {}", servConn.getName(), msg.getTransactionId(), batchId, numberOfEvents); } } private static void writeBatchException(Message origMsg, List<BatchException70> exceptions, ServerConnection servConn) throws IOException { Message errorMsg = servConn.getErrorResponseMessage(); errorMsg.setMessageType(MessageType.EXCEPTION); errorMsg.setNumberOfParts(2); errorMsg.setTransactionId(origMsg.getTransactionId()); errorMsg.addObjPart(exceptions); errorMsg.send(servConn); ((GatewayReceiverStats) servConn.getCacheServerStats()) .incExceptionsOccurred(exceptions.size()); for (Exception be : exceptions) { if (logger.isWarnEnabled()) { logger.warn(servConn.getName() + ": Wrote batch exception: ", be); } } } private static void writeFatalException(Message origMsg, Throwable exception, ServerConnection servConn) throws IOException { Message errorMsg = servConn.getErrorResponseMessage(); errorMsg.setMessageType(MessageType.EXCEPTION); errorMsg.setNumberOfParts(2); errorMsg.setTransactionId(origMsg.getTransactionId()); errorMsg.addObjPart(exception); errorMsg.send(servConn); logger.warn(servConn.getName() + ": Wrote batch exception: ", exception); } }
googleapis/google-cloud-java
36,446
java-gsuite-addons/proto-google-apps-script-type-protos/src/main/java/com/google/apps/script/type/sheets/SheetsAddOnManifest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/apps/script/type/sheets/sheets_addon_manifest.proto // Protobuf Java Version: 3.25.8 package com.google.apps.script.type.sheets; /** * * * <pre> * Sheets add-on manifest. * </pre> * * Protobuf type {@code google.apps.script.type.sheets.SheetsAddOnManifest} */ public final class SheetsAddOnManifest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.apps.script.type.sheets.SheetsAddOnManifest) SheetsAddOnManifestOrBuilder { private static final long serialVersionUID = 0L; // Use SheetsAddOnManifest.newBuilder() to construct. private SheetsAddOnManifest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SheetsAddOnManifest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SheetsAddOnManifest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.script.type.sheets.SheetsAddOnManifestProto .internal_static_google_apps_script_type_sheets_SheetsAddOnManifest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.script.type.sheets.SheetsAddOnManifestProto .internal_static_google_apps_script_type_sheets_SheetsAddOnManifest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.script.type.sheets.SheetsAddOnManifest.class, com.google.apps.script.type.sheets.SheetsAddOnManifest.Builder.class); } private int bitField0_; public static final int HOMEPAGE_TRIGGER_FIELD_NUMBER = 3; private com.google.apps.script.type.HomepageExtensionPoint homepageTrigger_; /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> * * @return Whether the homepageTrigger field is set. */ @java.lang.Override public boolean hasHomepageTrigger() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> * * @return The homepageTrigger. */ @java.lang.Override public com.google.apps.script.type.HomepageExtensionPoint getHomepageTrigger() { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ @java.lang.Override public com.google.apps.script.type.HomepageExtensionPointOrBuilder getHomepageTriggerOrBuilder() { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } public static final int ON_FILE_SCOPE_GRANTED_TRIGGER_FIELD_NUMBER = 5; private com.google.apps.script.type.sheets.SheetsExtensionPoint onFileScopeGrantedTrigger_; /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> * * @return Whether the onFileScopeGrantedTrigger field is set. */ @java.lang.Override public boolean hasOnFileScopeGrantedTrigger() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> * * @return The onFileScopeGrantedTrigger. */ @java.lang.Override public com.google.apps.script.type.sheets.SheetsExtensionPoint getOnFileScopeGrantedTrigger() { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.sheets.SheetsExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ @java.lang.Override public com.google.apps.script.type.sheets.SheetsExtensionPointOrBuilder getOnFileScopeGrantedTriggerOrBuilder() { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.sheets.SheetsExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getHomepageTrigger()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(5, getOnFileScopeGrantedTrigger()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getHomepageTrigger()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 5, getOnFileScopeGrantedTrigger()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.apps.script.type.sheets.SheetsAddOnManifest)) { return super.equals(obj); } com.google.apps.script.type.sheets.SheetsAddOnManifest other = (com.google.apps.script.type.sheets.SheetsAddOnManifest) obj; if (hasHomepageTrigger() != other.hasHomepageTrigger()) return false; if (hasHomepageTrigger()) { if (!getHomepageTrigger().equals(other.getHomepageTrigger())) return false; } if (hasOnFileScopeGrantedTrigger() != other.hasOnFileScopeGrantedTrigger()) return false; if (hasOnFileScopeGrantedTrigger()) { if (!getOnFileScopeGrantedTrigger().equals(other.getOnFileScopeGrantedTrigger())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasHomepageTrigger()) { hash = (37 * hash) + HOMEPAGE_TRIGGER_FIELD_NUMBER; hash = (53 * hash) + getHomepageTrigger().hashCode(); } if (hasOnFileScopeGrantedTrigger()) { hash = (37 * hash) + ON_FILE_SCOPE_GRANTED_TRIGGER_FIELD_NUMBER; hash = (53 * hash) + getOnFileScopeGrantedTrigger().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.apps.script.type.sheets.SheetsAddOnManifest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Sheets add-on manifest. * </pre> * * Protobuf type {@code google.apps.script.type.sheets.SheetsAddOnManifest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.apps.script.type.sheets.SheetsAddOnManifest) com.google.apps.script.type.sheets.SheetsAddOnManifestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.script.type.sheets.SheetsAddOnManifestProto .internal_static_google_apps_script_type_sheets_SheetsAddOnManifest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.script.type.sheets.SheetsAddOnManifestProto .internal_static_google_apps_script_type_sheets_SheetsAddOnManifest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.script.type.sheets.SheetsAddOnManifest.class, com.google.apps.script.type.sheets.SheetsAddOnManifest.Builder.class); } // Construct using com.google.apps.script.type.sheets.SheetsAddOnManifest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getHomepageTriggerFieldBuilder(); getOnFileScopeGrantedTriggerFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; homepageTrigger_ = null; if (homepageTriggerBuilder_ != null) { homepageTriggerBuilder_.dispose(); homepageTriggerBuilder_ = null; } onFileScopeGrantedTrigger_ = null; if (onFileScopeGrantedTriggerBuilder_ != null) { onFileScopeGrantedTriggerBuilder_.dispose(); onFileScopeGrantedTriggerBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.apps.script.type.sheets.SheetsAddOnManifestProto .internal_static_google_apps_script_type_sheets_SheetsAddOnManifest_descriptor; } @java.lang.Override public com.google.apps.script.type.sheets.SheetsAddOnManifest getDefaultInstanceForType() { return com.google.apps.script.type.sheets.SheetsAddOnManifest.getDefaultInstance(); } @java.lang.Override public com.google.apps.script.type.sheets.SheetsAddOnManifest build() { com.google.apps.script.type.sheets.SheetsAddOnManifest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.apps.script.type.sheets.SheetsAddOnManifest buildPartial() { com.google.apps.script.type.sheets.SheetsAddOnManifest result = new com.google.apps.script.type.sheets.SheetsAddOnManifest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.apps.script.type.sheets.SheetsAddOnManifest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.homepageTrigger_ = homepageTriggerBuilder_ == null ? homepageTrigger_ : homepageTriggerBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.onFileScopeGrantedTrigger_ = onFileScopeGrantedTriggerBuilder_ == null ? onFileScopeGrantedTrigger_ : onFileScopeGrantedTriggerBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.apps.script.type.sheets.SheetsAddOnManifest) { return mergeFrom((com.google.apps.script.type.sheets.SheetsAddOnManifest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.apps.script.type.sheets.SheetsAddOnManifest other) { if (other == com.google.apps.script.type.sheets.SheetsAddOnManifest.getDefaultInstance()) return this; if (other.hasHomepageTrigger()) { mergeHomepageTrigger(other.getHomepageTrigger()); } if (other.hasOnFileScopeGrantedTrigger()) { mergeOnFileScopeGrantedTrigger(other.getOnFileScopeGrantedTrigger()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 26: { input.readMessage(getHomepageTriggerFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 26 case 42: { input.readMessage( getOnFileScopeGrantedTriggerFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.apps.script.type.HomepageExtensionPoint homepageTrigger_; private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.HomepageExtensionPoint, com.google.apps.script.type.HomepageExtensionPoint.Builder, com.google.apps.script.type.HomepageExtensionPointOrBuilder> homepageTriggerBuilder_; /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> * * @return Whether the homepageTrigger field is set. */ public boolean hasHomepageTrigger() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> * * @return The homepageTrigger. */ public com.google.apps.script.type.HomepageExtensionPoint getHomepageTrigger() { if (homepageTriggerBuilder_ == null) { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } else { return homepageTriggerBuilder_.getMessage(); } } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ public Builder setHomepageTrigger(com.google.apps.script.type.HomepageExtensionPoint value) { if (homepageTriggerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } homepageTrigger_ = value; } else { homepageTriggerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ public Builder setHomepageTrigger( com.google.apps.script.type.HomepageExtensionPoint.Builder builderForValue) { if (homepageTriggerBuilder_ == null) { homepageTrigger_ = builderForValue.build(); } else { homepageTriggerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ public Builder mergeHomepageTrigger(com.google.apps.script.type.HomepageExtensionPoint value) { if (homepageTriggerBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && homepageTrigger_ != null && homepageTrigger_ != com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance()) { getHomepageTriggerBuilder().mergeFrom(value); } else { homepageTrigger_ = value; } } else { homepageTriggerBuilder_.mergeFrom(value); } if (homepageTrigger_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ public Builder clearHomepageTrigger() { bitField0_ = (bitField0_ & ~0x00000001); homepageTrigger_ = null; if (homepageTriggerBuilder_ != null) { homepageTriggerBuilder_.dispose(); homepageTriggerBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ public com.google.apps.script.type.HomepageExtensionPoint.Builder getHomepageTriggerBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHomepageTriggerFieldBuilder().getBuilder(); } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ public com.google.apps.script.type.HomepageExtensionPointOrBuilder getHomepageTriggerOrBuilder() { if (homepageTriggerBuilder_ != null) { return homepageTriggerBuilder_.getMessageOrBuilder(); } else { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.HomepageExtensionPoint, com.google.apps.script.type.HomepageExtensionPoint.Builder, com.google.apps.script.type.HomepageExtensionPointOrBuilder> getHomepageTriggerFieldBuilder() { if (homepageTriggerBuilder_ == null) { homepageTriggerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.HomepageExtensionPoint, com.google.apps.script.type.HomepageExtensionPoint.Builder, com.google.apps.script.type.HomepageExtensionPointOrBuilder>( getHomepageTrigger(), getParentForChildren(), isClean()); homepageTrigger_ = null; } return homepageTriggerBuilder_; } private com.google.apps.script.type.sheets.SheetsExtensionPoint onFileScopeGrantedTrigger_; private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.sheets.SheetsExtensionPoint, com.google.apps.script.type.sheets.SheetsExtensionPoint.Builder, com.google.apps.script.type.sheets.SheetsExtensionPointOrBuilder> onFileScopeGrantedTriggerBuilder_; /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> * * @return Whether the onFileScopeGrantedTrigger field is set. */ public boolean hasOnFileScopeGrantedTrigger() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> * * @return The onFileScopeGrantedTrigger. */ public com.google.apps.script.type.sheets.SheetsExtensionPoint getOnFileScopeGrantedTrigger() { if (onFileScopeGrantedTriggerBuilder_ == null) { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.sheets.SheetsExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } else { return onFileScopeGrantedTriggerBuilder_.getMessage(); } } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ public Builder setOnFileScopeGrantedTrigger( com.google.apps.script.type.sheets.SheetsExtensionPoint value) { if (onFileScopeGrantedTriggerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } onFileScopeGrantedTrigger_ = value; } else { onFileScopeGrantedTriggerBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ public Builder setOnFileScopeGrantedTrigger( com.google.apps.script.type.sheets.SheetsExtensionPoint.Builder builderForValue) { if (onFileScopeGrantedTriggerBuilder_ == null) { onFileScopeGrantedTrigger_ = builderForValue.build(); } else { onFileScopeGrantedTriggerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ public Builder mergeOnFileScopeGrantedTrigger( com.google.apps.script.type.sheets.SheetsExtensionPoint value) { if (onFileScopeGrantedTriggerBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && onFileScopeGrantedTrigger_ != null && onFileScopeGrantedTrigger_ != com.google.apps.script.type.sheets.SheetsExtensionPoint.getDefaultInstance()) { getOnFileScopeGrantedTriggerBuilder().mergeFrom(value); } else { onFileScopeGrantedTrigger_ = value; } } else { onFileScopeGrantedTriggerBuilder_.mergeFrom(value); } if (onFileScopeGrantedTrigger_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ public Builder clearOnFileScopeGrantedTrigger() { bitField0_ = (bitField0_ & ~0x00000002); onFileScopeGrantedTrigger_ = null; if (onFileScopeGrantedTriggerBuilder_ != null) { onFileScopeGrantedTriggerBuilder_.dispose(); onFileScopeGrantedTriggerBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ public com.google.apps.script.type.sheets.SheetsExtensionPoint.Builder getOnFileScopeGrantedTriggerBuilder() { bitField0_ |= 0x00000002; onChanged(); return getOnFileScopeGrantedTriggerFieldBuilder().getBuilder(); } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ public com.google.apps.script.type.sheets.SheetsExtensionPointOrBuilder getOnFileScopeGrantedTriggerOrBuilder() { if (onFileScopeGrantedTriggerBuilder_ != null) { return onFileScopeGrantedTriggerBuilder_.getMessageOrBuilder(); } else { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.sheets.SheetsExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.sheets.SheetsExtensionPoint on_file_scope_granted_trigger = 5; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.sheets.SheetsExtensionPoint, com.google.apps.script.type.sheets.SheetsExtensionPoint.Builder, com.google.apps.script.type.sheets.SheetsExtensionPointOrBuilder> getOnFileScopeGrantedTriggerFieldBuilder() { if (onFileScopeGrantedTriggerBuilder_ == null) { onFileScopeGrantedTriggerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.sheets.SheetsExtensionPoint, com.google.apps.script.type.sheets.SheetsExtensionPoint.Builder, com.google.apps.script.type.sheets.SheetsExtensionPointOrBuilder>( getOnFileScopeGrantedTrigger(), getParentForChildren(), isClean()); onFileScopeGrantedTrigger_ = null; } return onFileScopeGrantedTriggerBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.apps.script.type.sheets.SheetsAddOnManifest) } // @@protoc_insertion_point(class_scope:google.apps.script.type.sheets.SheetsAddOnManifest) private static final com.google.apps.script.type.sheets.SheetsAddOnManifest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.apps.script.type.sheets.SheetsAddOnManifest(); } public static com.google.apps.script.type.sheets.SheetsAddOnManifest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SheetsAddOnManifest> PARSER = new com.google.protobuf.AbstractParser<SheetsAddOnManifest>() { @java.lang.Override public SheetsAddOnManifest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SheetsAddOnManifest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SheetsAddOnManifest> getParserForType() { return PARSER; } @java.lang.Override public com.google.apps.script.type.sheets.SheetsAddOnManifest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,446
java-gsuite-addons/proto-google-apps-script-type-protos/src/main/java/com/google/apps/script/type/slides/SlidesAddOnManifest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/apps/script/type/slides/slides_addon_manifest.proto // Protobuf Java Version: 3.25.8 package com.google.apps.script.type.slides; /** * * * <pre> * Slides add-on manifest. * </pre> * * Protobuf type {@code google.apps.script.type.slides.SlidesAddOnManifest} */ public final class SlidesAddOnManifest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.apps.script.type.slides.SlidesAddOnManifest) SlidesAddOnManifestOrBuilder { private static final long serialVersionUID = 0L; // Use SlidesAddOnManifest.newBuilder() to construct. private SlidesAddOnManifest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SlidesAddOnManifest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SlidesAddOnManifest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.script.type.slides.SlidesAddOnManifestProto .internal_static_google_apps_script_type_slides_SlidesAddOnManifest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.script.type.slides.SlidesAddOnManifestProto .internal_static_google_apps_script_type_slides_SlidesAddOnManifest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.script.type.slides.SlidesAddOnManifest.class, com.google.apps.script.type.slides.SlidesAddOnManifest.Builder.class); } private int bitField0_; public static final int HOMEPAGE_TRIGGER_FIELD_NUMBER = 1; private com.google.apps.script.type.HomepageExtensionPoint homepageTrigger_; /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> * * @return Whether the homepageTrigger field is set. */ @java.lang.Override public boolean hasHomepageTrigger() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> * * @return The homepageTrigger. */ @java.lang.Override public com.google.apps.script.type.HomepageExtensionPoint getHomepageTrigger() { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ @java.lang.Override public com.google.apps.script.type.HomepageExtensionPointOrBuilder getHomepageTriggerOrBuilder() { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } public static final int ON_FILE_SCOPE_GRANTED_TRIGGER_FIELD_NUMBER = 2; private com.google.apps.script.type.slides.SlidesExtensionPoint onFileScopeGrantedTrigger_; /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> * * @return Whether the onFileScopeGrantedTrigger field is set. */ @java.lang.Override public boolean hasOnFileScopeGrantedTrigger() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> * * @return The onFileScopeGrantedTrigger. */ @java.lang.Override public com.google.apps.script.type.slides.SlidesExtensionPoint getOnFileScopeGrantedTrigger() { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.slides.SlidesExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ @java.lang.Override public com.google.apps.script.type.slides.SlidesExtensionPointOrBuilder getOnFileScopeGrantedTriggerOrBuilder() { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.slides.SlidesExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getHomepageTrigger()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getOnFileScopeGrantedTrigger()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getHomepageTrigger()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, getOnFileScopeGrantedTrigger()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.apps.script.type.slides.SlidesAddOnManifest)) { return super.equals(obj); } com.google.apps.script.type.slides.SlidesAddOnManifest other = (com.google.apps.script.type.slides.SlidesAddOnManifest) obj; if (hasHomepageTrigger() != other.hasHomepageTrigger()) return false; if (hasHomepageTrigger()) { if (!getHomepageTrigger().equals(other.getHomepageTrigger())) return false; } if (hasOnFileScopeGrantedTrigger() != other.hasOnFileScopeGrantedTrigger()) return false; if (hasOnFileScopeGrantedTrigger()) { if (!getOnFileScopeGrantedTrigger().equals(other.getOnFileScopeGrantedTrigger())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasHomepageTrigger()) { hash = (37 * hash) + HOMEPAGE_TRIGGER_FIELD_NUMBER; hash = (53 * hash) + getHomepageTrigger().hashCode(); } if (hasOnFileScopeGrantedTrigger()) { hash = (37 * hash) + ON_FILE_SCOPE_GRANTED_TRIGGER_FIELD_NUMBER; hash = (53 * hash) + getOnFileScopeGrantedTrigger().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.script.type.slides.SlidesAddOnManifest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.apps.script.type.slides.SlidesAddOnManifest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Slides add-on manifest. * </pre> * * Protobuf type {@code google.apps.script.type.slides.SlidesAddOnManifest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.apps.script.type.slides.SlidesAddOnManifest) com.google.apps.script.type.slides.SlidesAddOnManifestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.script.type.slides.SlidesAddOnManifestProto .internal_static_google_apps_script_type_slides_SlidesAddOnManifest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.script.type.slides.SlidesAddOnManifestProto .internal_static_google_apps_script_type_slides_SlidesAddOnManifest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.script.type.slides.SlidesAddOnManifest.class, com.google.apps.script.type.slides.SlidesAddOnManifest.Builder.class); } // Construct using com.google.apps.script.type.slides.SlidesAddOnManifest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getHomepageTriggerFieldBuilder(); getOnFileScopeGrantedTriggerFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; homepageTrigger_ = null; if (homepageTriggerBuilder_ != null) { homepageTriggerBuilder_.dispose(); homepageTriggerBuilder_ = null; } onFileScopeGrantedTrigger_ = null; if (onFileScopeGrantedTriggerBuilder_ != null) { onFileScopeGrantedTriggerBuilder_.dispose(); onFileScopeGrantedTriggerBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.apps.script.type.slides.SlidesAddOnManifestProto .internal_static_google_apps_script_type_slides_SlidesAddOnManifest_descriptor; } @java.lang.Override public com.google.apps.script.type.slides.SlidesAddOnManifest getDefaultInstanceForType() { return com.google.apps.script.type.slides.SlidesAddOnManifest.getDefaultInstance(); } @java.lang.Override public com.google.apps.script.type.slides.SlidesAddOnManifest build() { com.google.apps.script.type.slides.SlidesAddOnManifest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.apps.script.type.slides.SlidesAddOnManifest buildPartial() { com.google.apps.script.type.slides.SlidesAddOnManifest result = new com.google.apps.script.type.slides.SlidesAddOnManifest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.apps.script.type.slides.SlidesAddOnManifest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.homepageTrigger_ = homepageTriggerBuilder_ == null ? homepageTrigger_ : homepageTriggerBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.onFileScopeGrantedTrigger_ = onFileScopeGrantedTriggerBuilder_ == null ? onFileScopeGrantedTrigger_ : onFileScopeGrantedTriggerBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.apps.script.type.slides.SlidesAddOnManifest) { return mergeFrom((com.google.apps.script.type.slides.SlidesAddOnManifest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.apps.script.type.slides.SlidesAddOnManifest other) { if (other == com.google.apps.script.type.slides.SlidesAddOnManifest.getDefaultInstance()) return this; if (other.hasHomepageTrigger()) { mergeHomepageTrigger(other.getHomepageTrigger()); } if (other.hasOnFileScopeGrantedTrigger()) { mergeOnFileScopeGrantedTrigger(other.getOnFileScopeGrantedTrigger()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getHomepageTriggerFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( getOnFileScopeGrantedTriggerFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.apps.script.type.HomepageExtensionPoint homepageTrigger_; private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.HomepageExtensionPoint, com.google.apps.script.type.HomepageExtensionPoint.Builder, com.google.apps.script.type.HomepageExtensionPointOrBuilder> homepageTriggerBuilder_; /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> * * @return Whether the homepageTrigger field is set. */ public boolean hasHomepageTrigger() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> * * @return The homepageTrigger. */ public com.google.apps.script.type.HomepageExtensionPoint getHomepageTrigger() { if (homepageTriggerBuilder_ == null) { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } else { return homepageTriggerBuilder_.getMessage(); } } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ public Builder setHomepageTrigger(com.google.apps.script.type.HomepageExtensionPoint value) { if (homepageTriggerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } homepageTrigger_ = value; } else { homepageTriggerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ public Builder setHomepageTrigger( com.google.apps.script.type.HomepageExtensionPoint.Builder builderForValue) { if (homepageTriggerBuilder_ == null) { homepageTrigger_ = builderForValue.build(); } else { homepageTriggerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ public Builder mergeHomepageTrigger(com.google.apps.script.type.HomepageExtensionPoint value) { if (homepageTriggerBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && homepageTrigger_ != null && homepageTrigger_ != com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance()) { getHomepageTriggerBuilder().mergeFrom(value); } else { homepageTrigger_ = value; } } else { homepageTriggerBuilder_.mergeFrom(value); } if (homepageTrigger_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ public Builder clearHomepageTrigger() { bitField0_ = (bitField0_ & ~0x00000001); homepageTrigger_ = null; if (homepageTriggerBuilder_ != null) { homepageTriggerBuilder_.dispose(); homepageTriggerBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ public com.google.apps.script.type.HomepageExtensionPoint.Builder getHomepageTriggerBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHomepageTriggerFieldBuilder().getBuilder(); } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ public com.google.apps.script.type.HomepageExtensionPointOrBuilder getHomepageTriggerOrBuilder() { if (homepageTriggerBuilder_ != null) { return homepageTriggerBuilder_.getMessageOrBuilder(); } else { return homepageTrigger_ == null ? com.google.apps.script.type.HomepageExtensionPoint.getDefaultInstance() : homepageTrigger_; } } /** * * * <pre> * If present, this overrides the configuration from * `addOns.common.homepageTrigger`. * </pre> * * <code>.google.apps.script.type.HomepageExtensionPoint homepage_trigger = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.HomepageExtensionPoint, com.google.apps.script.type.HomepageExtensionPoint.Builder, com.google.apps.script.type.HomepageExtensionPointOrBuilder> getHomepageTriggerFieldBuilder() { if (homepageTriggerBuilder_ == null) { homepageTriggerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.HomepageExtensionPoint, com.google.apps.script.type.HomepageExtensionPoint.Builder, com.google.apps.script.type.HomepageExtensionPointOrBuilder>( getHomepageTrigger(), getParentForChildren(), isClean()); homepageTrigger_ = null; } return homepageTriggerBuilder_; } private com.google.apps.script.type.slides.SlidesExtensionPoint onFileScopeGrantedTrigger_; private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.slides.SlidesExtensionPoint, com.google.apps.script.type.slides.SlidesExtensionPoint.Builder, com.google.apps.script.type.slides.SlidesExtensionPointOrBuilder> onFileScopeGrantedTriggerBuilder_; /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> * * @return Whether the onFileScopeGrantedTrigger field is set. */ public boolean hasOnFileScopeGrantedTrigger() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> * * @return The onFileScopeGrantedTrigger. */ public com.google.apps.script.type.slides.SlidesExtensionPoint getOnFileScopeGrantedTrigger() { if (onFileScopeGrantedTriggerBuilder_ == null) { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.slides.SlidesExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } else { return onFileScopeGrantedTriggerBuilder_.getMessage(); } } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ public Builder setOnFileScopeGrantedTrigger( com.google.apps.script.type.slides.SlidesExtensionPoint value) { if (onFileScopeGrantedTriggerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } onFileScopeGrantedTrigger_ = value; } else { onFileScopeGrantedTriggerBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ public Builder setOnFileScopeGrantedTrigger( com.google.apps.script.type.slides.SlidesExtensionPoint.Builder builderForValue) { if (onFileScopeGrantedTriggerBuilder_ == null) { onFileScopeGrantedTrigger_ = builderForValue.build(); } else { onFileScopeGrantedTriggerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ public Builder mergeOnFileScopeGrantedTrigger( com.google.apps.script.type.slides.SlidesExtensionPoint value) { if (onFileScopeGrantedTriggerBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && onFileScopeGrantedTrigger_ != null && onFileScopeGrantedTrigger_ != com.google.apps.script.type.slides.SlidesExtensionPoint.getDefaultInstance()) { getOnFileScopeGrantedTriggerBuilder().mergeFrom(value); } else { onFileScopeGrantedTrigger_ = value; } } else { onFileScopeGrantedTriggerBuilder_.mergeFrom(value); } if (onFileScopeGrantedTrigger_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ public Builder clearOnFileScopeGrantedTrigger() { bitField0_ = (bitField0_ & ~0x00000002); onFileScopeGrantedTrigger_ = null; if (onFileScopeGrantedTriggerBuilder_ != null) { onFileScopeGrantedTriggerBuilder_.dispose(); onFileScopeGrantedTriggerBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ public com.google.apps.script.type.slides.SlidesExtensionPoint.Builder getOnFileScopeGrantedTriggerBuilder() { bitField0_ |= 0x00000002; onChanged(); return getOnFileScopeGrantedTriggerFieldBuilder().getBuilder(); } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ public com.google.apps.script.type.slides.SlidesExtensionPointOrBuilder getOnFileScopeGrantedTriggerOrBuilder() { if (onFileScopeGrantedTriggerBuilder_ != null) { return onFileScopeGrantedTriggerBuilder_.getMessageOrBuilder(); } else { return onFileScopeGrantedTrigger_ == null ? com.google.apps.script.type.slides.SlidesExtensionPoint.getDefaultInstance() : onFileScopeGrantedTrigger_; } } /** * * * <pre> * Endpoint to execute when file scope authorization is granted * for this document/user pair. * </pre> * * <code>.google.apps.script.type.slides.SlidesExtensionPoint on_file_scope_granted_trigger = 2; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.slides.SlidesExtensionPoint, com.google.apps.script.type.slides.SlidesExtensionPoint.Builder, com.google.apps.script.type.slides.SlidesExtensionPointOrBuilder> getOnFileScopeGrantedTriggerFieldBuilder() { if (onFileScopeGrantedTriggerBuilder_ == null) { onFileScopeGrantedTriggerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.apps.script.type.slides.SlidesExtensionPoint, com.google.apps.script.type.slides.SlidesExtensionPoint.Builder, com.google.apps.script.type.slides.SlidesExtensionPointOrBuilder>( getOnFileScopeGrantedTrigger(), getParentForChildren(), isClean()); onFileScopeGrantedTrigger_ = null; } return onFileScopeGrantedTriggerBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.apps.script.type.slides.SlidesAddOnManifest) } // @@protoc_insertion_point(class_scope:google.apps.script.type.slides.SlidesAddOnManifest) private static final com.google.apps.script.type.slides.SlidesAddOnManifest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.apps.script.type.slides.SlidesAddOnManifest(); } public static com.google.apps.script.type.slides.SlidesAddOnManifest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SlidesAddOnManifest> PARSER = new com.google.protobuf.AbstractParser<SlidesAddOnManifest>() { @java.lang.Override public SlidesAddOnManifest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SlidesAddOnManifest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SlidesAddOnManifest> getParserForType() { return PARSER; } @java.lang.Override public com.google.apps.script.type.slides.SlidesAddOnManifest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,654
java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonSnapshotsStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.compute.v1.stub; import static com.google.cloud.compute.v1.SnapshotsClient.ListPagedResponse; import com.google.api.core.InternalApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.httpjson.ApiMethodDescriptor; import com.google.api.gax.httpjson.HttpJsonCallSettings; import com.google.api.gax.httpjson.HttpJsonOperationSnapshot; import com.google.api.gax.httpjson.HttpJsonStubCallableFactory; import com.google.api.gax.httpjson.ProtoMessageRequestFormatter; import com.google.api.gax.httpjson.ProtoMessageResponseParser; import com.google.api.gax.httpjson.ProtoRestSerializer; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.compute.v1.DeleteSnapshotRequest; import com.google.cloud.compute.v1.GetIamPolicySnapshotRequest; import com.google.cloud.compute.v1.GetSnapshotRequest; import com.google.cloud.compute.v1.InsertSnapshotRequest; import com.google.cloud.compute.v1.ListSnapshotsRequest; import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.Operation.Status; import com.google.cloud.compute.v1.Policy; import com.google.cloud.compute.v1.SetIamPolicySnapshotRequest; import com.google.cloud.compute.v1.SetLabelsSnapshotRequest; import com.google.cloud.compute.v1.Snapshot; import com.google.cloud.compute.v1.SnapshotList; import com.google.cloud.compute.v1.TestIamPermissionsSnapshotRequest; import com.google.cloud.compute.v1.TestPermissionsResponse; import com.google.protobuf.TypeRegistry; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * REST stub implementation for the Snapshots service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonSnapshotsStub extends SnapshotsStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder().add(Operation.getDescriptor()).build(); private static final ApiMethodDescriptor<DeleteSnapshotRequest, Operation> deleteMethodDescriptor = ApiMethodDescriptor.<DeleteSnapshotRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/Delete") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeleteSnapshotRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots/{snapshot}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeleteSnapshotRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "snapshot", request.getSnapshot()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeleteSnapshotRequest> serializer = ProtoRestSerializer.create(); if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeleteSnapshotRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor<GetSnapshotRequest, Snapshot> getMethodDescriptor = ApiMethodDescriptor.<GetSnapshotRequest, Snapshot>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/Get") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetSnapshotRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots/{snapshot}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetSnapshotRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "snapshot", request.getSnapshot()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetSnapshotRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Snapshot>newBuilder() .setDefaultInstance(Snapshot.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetIamPolicySnapshotRequest, Policy> getIamPolicyMethodDescriptor = ApiMethodDescriptor.<GetIamPolicySnapshotRequest, Policy>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/GetIamPolicy") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetIamPolicySnapshotRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots/{resource}/getIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicySnapshotRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicySnapshotRequest> serializer = ProtoRestSerializer.create(); if (request.hasOptionsRequestedPolicyVersion()) { serializer.putQueryParam( fields, "optionsRequestedPolicyVersion", request.getOptionsRequestedPolicyVersion()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<InsertSnapshotRequest, Operation> insertMethodDescriptor = ApiMethodDescriptor.<InsertSnapshotRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/Insert") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<InsertSnapshotRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<InsertSnapshotRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<InsertSnapshotRequest> serializer = ProtoRestSerializer.create(); if (request.hasRequestId()) { serializer.putQueryParam(fields, "requestId", request.getRequestId()); } return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("snapshotResource", request.getSnapshotResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (InsertSnapshotRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor<ListSnapshotsRequest, SnapshotList> listMethodDescriptor = ApiMethodDescriptor.<ListSnapshotsRequest, SnapshotList>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/List") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListSnapshotsRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListSnapshotsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListSnapshotsRequest> serializer = ProtoRestSerializer.create(); if (request.hasFilter()) { serializer.putQueryParam(fields, "filter", request.getFilter()); } if (request.hasMaxResults()) { serializer.putQueryParam( fields, "maxResults", request.getMaxResults()); } if (request.hasOrderBy()) { serializer.putQueryParam(fields, "orderBy", request.getOrderBy()); } if (request.hasPageToken()) { serializer.putQueryParam(fields, "pageToken", request.getPageToken()); } if (request.hasReturnPartialSuccess()) { serializer.putQueryParam( fields, "returnPartialSuccess", request.getReturnPartialSuccess()); } return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<SnapshotList>newBuilder() .setDefaultInstance(SnapshotList.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<SetIamPolicySnapshotRequest, Policy> setIamPolicyMethodDescriptor = ApiMethodDescriptor.<SetIamPolicySnapshotRequest, Policy>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/SetIamPolicy") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<SetIamPolicySnapshotRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots/{resource}/setIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicySnapshotRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicySnapshotRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "globalSetPolicyRequestResource", request.getGlobalSetPolicyRequestResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<SetLabelsSnapshotRequest, Operation> setLabelsMethodDescriptor = ApiMethodDescriptor.<SetLabelsSnapshotRequest, Operation>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/SetLabels") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<SetLabelsSnapshotRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots/{resource}/setLabels", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<SetLabelsSnapshotRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<SetLabelsSnapshotRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "globalSetLabelsRequestResource", request.getGlobalSetLabelsRequestResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (SetLabelsSnapshotRequest request, Operation response) -> { StringBuilder opName = new StringBuilder(response.getName()); opName.append(":").append(request.getProject()); return HttpJsonOperationSnapshot.newBuilder() .setName(opName.toString()) .setMetadata(response) .setDone(Status.DONE.equals(response.getStatus())) .setResponse(response) .setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage()) .build(); }) .build(); private static final ApiMethodDescriptor< TestIamPermissionsSnapshotRequest, TestPermissionsResponse> testIamPermissionsMethodDescriptor = ApiMethodDescriptor .<TestIamPermissionsSnapshotRequest, TestPermissionsResponse>newBuilder() .setFullMethodName("google.cloud.compute.v1.Snapshots/TestIamPermissions") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<TestIamPermissionsSnapshotRequest>newBuilder() .setPath( "/compute/v1/projects/{project}/global/snapshots/{resource}/testIamPermissions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsSnapshotRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "project", request.getProject()); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsSnapshotRequest> serializer = ProtoRestSerializer.create(); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody( "testPermissionsRequestResource", request.getTestPermissionsRequestResource(), false)) .build()) .setResponseParser( ProtoMessageResponseParser.<TestPermissionsResponse>newBuilder() .setDefaultInstance(TestPermissionsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<DeleteSnapshotRequest, Operation> deleteCallable; private final OperationCallable<DeleteSnapshotRequest, Operation, Operation> deleteOperationCallable; private final UnaryCallable<GetSnapshotRequest, Snapshot> getCallable; private final UnaryCallable<GetIamPolicySnapshotRequest, Policy> getIamPolicyCallable; private final UnaryCallable<InsertSnapshotRequest, Operation> insertCallable; private final OperationCallable<InsertSnapshotRequest, Operation, Operation> insertOperationCallable; private final UnaryCallable<ListSnapshotsRequest, SnapshotList> listCallable; private final UnaryCallable<ListSnapshotsRequest, ListPagedResponse> listPagedCallable; private final UnaryCallable<SetIamPolicySnapshotRequest, Policy> setIamPolicyCallable; private final UnaryCallable<SetLabelsSnapshotRequest, Operation> setLabelsCallable; private final OperationCallable<SetLabelsSnapshotRequest, Operation, Operation> setLabelsOperationCallable; private final UnaryCallable<TestIamPermissionsSnapshotRequest, TestPermissionsResponse> testIamPermissionsCallable; private final BackgroundResource backgroundResources; private final HttpJsonGlobalOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonSnapshotsStub create(SnapshotsStubSettings settings) throws IOException { return new HttpJsonSnapshotsStub(settings, ClientContext.create(settings)); } public static final HttpJsonSnapshotsStub create(ClientContext clientContext) throws IOException { return new HttpJsonSnapshotsStub(SnapshotsStubSettings.newBuilder().build(), clientContext); } public static final HttpJsonSnapshotsStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonSnapshotsStub( SnapshotsStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonSnapshotsStub, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonSnapshotsStub(SnapshotsStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonSnapshotsCallableFactory()); } /** * Constructs an instance of HttpJsonSnapshotsStub, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonSnapshotsStub( SnapshotsStubSettings settings, ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.httpJsonOperationsStub = HttpJsonGlobalOperationsStub.create(clientContext, callableFactory); HttpJsonCallSettings<DeleteSnapshotRequest, Operation> deleteTransportSettings = HttpJsonCallSettings.<DeleteSnapshotRequest, Operation>newBuilder() .setMethodDescriptor(deleteMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("snapshot", String.valueOf(request.getSnapshot())); return builder.build(); }) .build(); HttpJsonCallSettings<GetSnapshotRequest, Snapshot> getTransportSettings = HttpJsonCallSettings.<GetSnapshotRequest, Snapshot>newBuilder() .setMethodDescriptor(getMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("snapshot", String.valueOf(request.getSnapshot())); return builder.build(); }) .build(); HttpJsonCallSettings<GetIamPolicySnapshotRequest, Policy> getIamPolicyTransportSettings = HttpJsonCallSettings.<GetIamPolicySnapshotRequest, Policy>newBuilder() .setMethodDescriptor(getIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<InsertSnapshotRequest, Operation> insertTransportSettings = HttpJsonCallSettings.<InsertSnapshotRequest, Operation>newBuilder() .setMethodDescriptor(insertMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); return builder.build(); }) .build(); HttpJsonCallSettings<ListSnapshotsRequest, SnapshotList> listTransportSettings = HttpJsonCallSettings.<ListSnapshotsRequest, SnapshotList>newBuilder() .setMethodDescriptor(listMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); return builder.build(); }) .build(); HttpJsonCallSettings<SetIamPolicySnapshotRequest, Policy> setIamPolicyTransportSettings = HttpJsonCallSettings.<SetIamPolicySnapshotRequest, Policy>newBuilder() .setMethodDescriptor(setIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<SetLabelsSnapshotRequest, Operation> setLabelsTransportSettings = HttpJsonCallSettings.<SetLabelsSnapshotRequest, Operation>newBuilder() .setMethodDescriptor(setLabelsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<TestIamPermissionsSnapshotRequest, TestPermissionsResponse> testIamPermissionsTransportSettings = HttpJsonCallSettings .<TestIamPermissionsSnapshotRequest, TestPermissionsResponse>newBuilder() .setMethodDescriptor(testIamPermissionsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("project", String.valueOf(request.getProject())); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); this.deleteCallable = callableFactory.createUnaryCallable( deleteTransportSettings, settings.deleteSettings(), clientContext); this.deleteOperationCallable = callableFactory.createOperationCallable( deleteTransportSettings, settings.deleteOperationSettings(), clientContext, httpJsonOperationsStub); this.getCallable = callableFactory.createUnaryCallable( getTransportSettings, settings.getSettings(), clientContext); this.getIamPolicyCallable = callableFactory.createUnaryCallable( getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); this.insertCallable = callableFactory.createUnaryCallable( insertTransportSettings, settings.insertSettings(), clientContext); this.insertOperationCallable = callableFactory.createOperationCallable( insertTransportSettings, settings.insertOperationSettings(), clientContext, httpJsonOperationsStub); this.listCallable = callableFactory.createUnaryCallable( listTransportSettings, settings.listSettings(), clientContext); this.listPagedCallable = callableFactory.createPagedCallable( listTransportSettings, settings.listSettings(), clientContext); this.setIamPolicyCallable = callableFactory.createUnaryCallable( setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); this.setLabelsCallable = callableFactory.createUnaryCallable( setLabelsTransportSettings, settings.setLabelsSettings(), clientContext); this.setLabelsOperationCallable = callableFactory.createOperationCallable( setLabelsTransportSettings, settings.setLabelsOperationSettings(), clientContext, httpJsonOperationsStub); this.testIamPermissionsCallable = callableFactory.createUnaryCallable( testIamPermissionsTransportSettings, settings.testIamPermissionsSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } @InternalApi public static List<ApiMethodDescriptor> getMethodDescriptors() { List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>(); methodDescriptors.add(deleteMethodDescriptor); methodDescriptors.add(getMethodDescriptor); methodDescriptors.add(getIamPolicyMethodDescriptor); methodDescriptors.add(insertMethodDescriptor); methodDescriptors.add(listMethodDescriptor); methodDescriptors.add(setIamPolicyMethodDescriptor); methodDescriptors.add(setLabelsMethodDescriptor); methodDescriptors.add(testIamPermissionsMethodDescriptor); return methodDescriptors; } @Override public UnaryCallable<DeleteSnapshotRequest, Operation> deleteCallable() { return deleteCallable; } @Override public OperationCallable<DeleteSnapshotRequest, Operation, Operation> deleteOperationCallable() { return deleteOperationCallable; } @Override public UnaryCallable<GetSnapshotRequest, Snapshot> getCallable() { return getCallable; } @Override public UnaryCallable<GetIamPolicySnapshotRequest, Policy> getIamPolicyCallable() { return getIamPolicyCallable; } @Override public UnaryCallable<InsertSnapshotRequest, Operation> insertCallable() { return insertCallable; } @Override public OperationCallable<InsertSnapshotRequest, Operation, Operation> insertOperationCallable() { return insertOperationCallable; } @Override public UnaryCallable<ListSnapshotsRequest, SnapshotList> listCallable() { return listCallable; } @Override public UnaryCallable<ListSnapshotsRequest, ListPagedResponse> listPagedCallable() { return listPagedCallable; } @Override public UnaryCallable<SetIamPolicySnapshotRequest, Policy> setIamPolicyCallable() { return setIamPolicyCallable; } @Override public UnaryCallable<SetLabelsSnapshotRequest, Operation> setLabelsCallable() { return setLabelsCallable; } @Override public OperationCallable<SetLabelsSnapshotRequest, Operation, Operation> setLabelsOperationCallable() { return setLabelsOperationCallable; } @Override public UnaryCallable<TestIamPermissionsSnapshotRequest, TestPermissionsResponse> testIamPermissionsCallable() { return testIamPermissionsCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
apache/fineract
36,958
fineract-provider/src/main/java/org/apache/fineract/portfolio/savings/domain/DepositAccountDomainServiceJpa.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.portfolio.savings.domain; import static org.apache.fineract.portfolio.savings.DepositsApiConstants.onAccountClosureIdParamName; import static org.apache.fineract.portfolio.savings.DepositsApiConstants.toSavingsAccountIdParamName; import static org.apache.fineract.portfolio.savings.DepositsApiConstants.transferDescriptionParamName; import java.math.BigDecimal; import java.math.MathContext; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.fineract.accounting.journalentry.service.JournalEntryWritePlatformService; import org.apache.fineract.infrastructure.accountnumberformat.domain.AccountNumberFormat; import org.apache.fineract.infrastructure.accountnumberformat.domain.AccountNumberFormatRepositoryWrapper; import org.apache.fineract.infrastructure.accountnumberformat.domain.EntityAccountType; import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.domain.ExternalId; import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException; import org.apache.fineract.infrastructure.core.service.DateUtils; import org.apache.fineract.portfolio.account.PortfolioAccountType; import org.apache.fineract.portfolio.account.data.AccountTransferDTO; import org.apache.fineract.portfolio.account.domain.AccountTransferType; import org.apache.fineract.portfolio.account.service.AccountNumberGenerator; import org.apache.fineract.portfolio.account.service.AccountTransfersWritePlatformService; import org.apache.fineract.portfolio.calendar.domain.Calendar; import org.apache.fineract.portfolio.calendar.domain.CalendarEntityType; import org.apache.fineract.portfolio.calendar.domain.CalendarFrequencyType; import org.apache.fineract.portfolio.calendar.domain.CalendarInstance; import org.apache.fineract.portfolio.calendar.domain.CalendarInstanceRepository; import org.apache.fineract.portfolio.calendar.domain.CalendarType; import org.apache.fineract.portfolio.calendar.service.CalendarUtils; import org.apache.fineract.portfolio.common.domain.PeriodFrequencyType; import org.apache.fineract.portfolio.paymentdetail.domain.PaymentDetail; import org.apache.fineract.portfolio.savings.DepositAccountOnClosureType; import org.apache.fineract.portfolio.savings.DepositAccountType; import org.apache.fineract.portfolio.savings.DepositsApiConstants; import org.apache.fineract.portfolio.savings.SavingsApiConstants; import org.apache.fineract.portfolio.savings.SavingsTransactionBooleanValues; import org.apache.fineract.portfolio.savings.service.SavingsAccountDomainService; import org.apache.fineract.useradministration.domain.AppUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class DepositAccountDomainServiceJpa implements DepositAccountDomainService { private final SavingsAccountRepositoryWrapper savingsAccountRepository; private final JournalEntryWritePlatformService journalEntryWritePlatformService; private final AccountNumberGenerator accountNumberGenerator; private final DepositAccountAssembler depositAccountAssembler; private final SavingsAccountDomainService savingsAccountDomainService; private final AccountTransfersWritePlatformService accountTransfersWritePlatformService; private final ConfigurationDomainService configurationDomainService; private final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository; private final CalendarInstanceRepository calendarInstanceRepository; @Autowired public DepositAccountDomainServiceJpa(final SavingsAccountRepositoryWrapper savingsAccountRepository, final JournalEntryWritePlatformService journalEntryWritePlatformService, final AccountNumberGenerator accountNumberGenerator, final DepositAccountAssembler depositAccountAssembler, final SavingsAccountDomainService savingsAccountDomainService, final AccountTransfersWritePlatformService accountTransfersWritePlatformService, final ConfigurationDomainService configurationDomainService, final AccountNumberFormatRepositoryWrapper accountNumberFormatRepository, final CalendarInstanceRepository calendarInstanceRepository) { this.savingsAccountRepository = savingsAccountRepository; this.journalEntryWritePlatformService = journalEntryWritePlatformService; this.accountNumberGenerator = accountNumberGenerator; this.depositAccountAssembler = depositAccountAssembler; this.savingsAccountDomainService = savingsAccountDomainService; this.accountTransfersWritePlatformService = accountTransfersWritePlatformService; this.configurationDomainService = configurationDomainService; this.accountNumberFormatRepository = accountNumberFormatRepository; this.calendarInstanceRepository = calendarInstanceRepository; } @Transactional @Override public SavingsAccountTransaction handleWithdrawal(final SavingsAccount account, final DateTimeFormatter fmt, final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail, final boolean applyWithdrawFee, final boolean isRegularTransaction) { boolean isAccountTransfer = false; boolean isInterestTransfer = false; boolean isWithdrawBalance = false; final boolean backdatedTxnsAllowedTill = false; SavingsTransactionBooleanValues transactionBooleanValues = new SavingsTransactionBooleanValues(isAccountTransfer, isRegularTransaction, applyWithdrawFee, isInterestTransfer, isWithdrawBalance); return this.savingsAccountDomainService.handleWithdrawal(account, fmt, transactionDate, transactionAmount, paymentDetail, transactionBooleanValues, backdatedTxnsAllowedTill); } @Transactional @Override public SavingsAccountTransaction handleFDDeposit(final FixedDepositAccount account, final DateTimeFormatter fmt, final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail) { boolean isAccountTransfer = false; boolean isRegularTransaction = false; final boolean backdatedTxnsAllowedTill = false; return this.savingsAccountDomainService.handleDeposit(account, fmt, transactionDate, transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill); } @Transactional @Override public SavingsAccountTransaction handleRDDeposit(final RecurringDepositAccount account, final DateTimeFormatter fmt, final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail, final boolean isRegularTransaction) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); boolean isAccountTransfer = false; final boolean isPreMatureClosure = false; final MathContext mc = MathContext.DECIMAL64; account.updateDepositAmount(transactionAmount); final boolean backdatedTxnsAllowedTill = false; final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(account, fmt, transactionDate, transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill); final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); final boolean isAnyActivationChargesDue = isAnyActivationChargesDue(account); if (isAnyActivationChargesDue) { updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); account.processAccountUponActivation(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); this.savingsAccountRepository.saveAndFlush(account); } account.handleScheduleInstallments(deposit); account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); account.updateOverduePayments(DateUtils.getBusinessLocalDate()); if (isAnyActivationChargesDue) { postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); } return deposit; } @Transactional @Override public SavingsAccountTransaction handleSavingDeposit(final SavingsAccount account, final DateTimeFormatter fmt, final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail, final boolean isRegularTransaction) { boolean isAccountTransfer = false; final boolean backdatedTxnsAllowedTill = false; final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(account, fmt, transactionDate, transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill); final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); return deposit; } private boolean isAnyActivationChargesDue(final RecurringDepositAccount account) { for (final SavingsAccountCharge savingsAccountCharge : account.charges()) { if (savingsAccountCharge.isSavingsActivation() && savingsAccountCharge.amoutOutstanding() != null && savingsAccountCharge.amoutOutstanding().compareTo(BigDecimal.ZERO) > 0) { return true; } } return false; } @Transactional @Override public Long handleFDAccountClosure(final FixedDepositAccount account, final PaymentDetail paymentDetail, final AppUser user, final JsonCommand command, final Map<String, Object> changes) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); boolean isRegularTransaction = false; boolean isAccountTransfer = false; final boolean isPreMatureClosure = false; final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); // Update account transactionIds for post journal entries. updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); /* * final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, * transactionAmount, paymentDetail, new Date()); final SavingsAccountTransaction deposit = * account.deposit(transactionDTO); boolean isInterestTransfer = false; final MathContext mc = * MathContext.DECIMAL64; if (account.isBeforeLastPostingPeriod(transactionDate)) { final LocalDate today = * DateUtils.getLocalDateOfTenant(); account.postInterest(mc, today, isInterestTransfer); } else { final * LocalDate today = DateUtils.getLocalDateOfTenant(); account.calculateInterestUsing(mc, today, * isInterestTransfer); ======= */ final MathContext mc = MathContext.DECIMAL64; final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale); final LocalDate closedDate = command.localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName); Long savingsTransactionId = null; account.postMaturityInterest(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); account.setClosedOnDate(closedDate); final Integer onAccountClosureId = command.integerValueOfParameterNamed(onAccountClosureIdParamName); final DepositAccountOnClosureType onClosureType = DepositAccountOnClosureType.fromInt(onAccountClosureId); if (onClosureType.isReinvest()) { FixedDepositAccount reinvestedDeposit = account.reInvest(account.getAccountBalance()); this.depositAccountAssembler.assignSavingAccountHelpers(reinvestedDeposit); reinvestedDeposit.updateMaturityDateAndAmountBeforeAccountActivation(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); this.savingsAccountRepository.save(reinvestedDeposit); autoGenerateAccountNumber(reinvestedDeposit); final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(), paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); } else if (onClosureType.isTransferToSavings()) { final Long toSavingsId = command.longValueOfParameterNamed(toSavingsAccountIdParamName); final String transferDescription = command.stringValueOfParameterNamed(transferDescriptionParamName); final SavingsAccount toSavingsAccount = this.depositAccountAssembler.assembleFrom(toSavingsId, DepositAccountType.SAVINGS_DEPOSIT); final boolean isExceptionForBalanceCheck = false; final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(closedDate, account.getAccountBalance(), PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, transferDescription, locale, fmt, null, null, null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, account, isAccountTransfer, isExceptionForBalanceCheck); this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); updateAlreadyPostedTransactions(existingTransactionIds, account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); } else { final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(), paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); } account.close(user, command, changes); this.savingsAccountRepository.save(account); return savingsTransactionId; } @Transactional @Override public Long handleFDAccountMaturityClosure(final FixedDepositAccount account, final PaymentDetail paymentDetail, final AppUser user, final DateTimeFormatter fmt, final LocalDate closedDate, final Integer onAccountClosureId, final Long toSavingsId, final String transferDescription, Map<String, Object> changes) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); boolean isRegularTransaction = false; boolean isAccountTransfer = false; final boolean isPreMatureClosure = false; final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); /*** * Update account transactionIds for post journal entries. */ updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); final MathContext mc = MathContext.DECIMAL64; Long savingsTransactionId = null; account.postMaturityInterest(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); account.setClosedOnDate(closedDate); final DepositAccountOnClosureType onClosureType = DepositAccountOnClosureType.fromInt(onAccountClosureId); if (onClosureType.isReinvest()) { BigDecimal reInvestAmount; if (onClosureType.isReinvestPrincipal()) { reInvestAmount = account.getDepositAmount(); } else { reInvestAmount = account.getAccountBalance(); } FixedDepositAccount reinvestedDeposit = account.reInvest(reInvestAmount); this.depositAccountAssembler.assignSavingAccountHelpers(reinvestedDeposit); reinvestedDeposit.updateMaturityDateAndAmountBeforeAccountActivation(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); this.savingsAccountRepository.save(reinvestedDeposit); autoGenerateAccountNumber(reinvestedDeposit); final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, reInvestAmount, paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); if (onClosureType.isReinvestPrincipalAndInterest()) { account.updateClosedStatus(); account.updateOnAccountClosureStatus(onClosureType); } changes.put("reinvestedDepositId", reinvestedDeposit.getId()); reinvestedDeposit.approveAndActivateApplication(closedDate, user); this.savingsAccountRepository.save(reinvestedDeposit); } else if (onClosureType.isTransferToSavings()) { final SavingsAccount toSavingsAccount = this.depositAccountAssembler.assembleFrom(toSavingsId, DepositAccountType.SAVINGS_DEPOSIT); final boolean isExceptionForBalanceCheck = false; final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(closedDate, account.getAccountBalance(), PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, transferDescription, null, fmt, null, null, null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, account, isAccountTransfer, isExceptionForBalanceCheck); this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); updateAlreadyPostedTransactions(existingTransactionIds, account); account.updateClosedStatus(); account.updateOnAccountClosureStatus(onClosureType); } else { final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(), paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); } // if(!processMaturityInstructionOnly) // account.close(user, command, changes); this.savingsAccountRepository.save(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); return savingsTransactionId; } @Transactional @Override public Long handleRDAccountClosure(final RecurringDepositAccount account, final PaymentDetail paymentDetail, final AppUser user, final JsonCommand command, final Map<String, Object> changes) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); final boolean postReversals = false; boolean isRegularTransaction = false; boolean isAccountTransfer = false; final boolean isPreMatureClosure = false; final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); // Update account transactionIds for post journal entries. updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); final MathContext mc = MathContext.DECIMAL64; final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale); final LocalDate closedDate = command.localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName); Long savingsTransactionId = null; account.postMaturityInterest(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, closedDate, postReversals); final BigDecimal transactionAmount = account.getAccountBalance(); final Integer onAccountClosureId = command.integerValueOfParameterNamed(onAccountClosureIdParamName); final DepositAccountOnClosureType onClosureType = DepositAccountOnClosureType.fromInt(onAccountClosureId); if (onClosureType.isReinvest()) { BigDecimal reInvestAmount; if (onClosureType.isReinvestPrincipal()) { reInvestAmount = account.getDepositAmount(); } else { reInvestAmount = account.getAccountBalance(); } RecurringDepositAccount reinvestedDeposit = account.reInvest(reInvestAmount); depositAccountAssembler.assignSavingAccountHelpers(reinvestedDeposit); this.savingsAccountRepository.save(reinvestedDeposit); final CalendarInstance calendarInstance = getCalendarInstance(account, reinvestedDeposit); this.calendarInstanceRepository.save(calendarInstance); final Calendar calendar = calendarInstance.getCalendar(); final PeriodFrequencyType frequencyType = CalendarFrequencyType.from(CalendarUtils.getFrequency(calendar.getRecurrence())); final Long relaxingDaysConfigForPivotDate = this.configurationDomainService.retrieveRelaxingDaysConfigForPivotDate(); Integer frequency = CalendarUtils.getInterval(calendar.getRecurrence()); frequency = frequency == -1 ? 1 : frequency; reinvestedDeposit.generateSchedule(frequencyType, frequency, calendar); reinvestedDeposit.processAccountUponActivation(fmt, postReversals, relaxingDaysConfigForPivotDate); reinvestedDeposit.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); this.savingsAccountRepository.save(reinvestedDeposit); autoGenerateAccountNumber(reinvestedDeposit); final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(), paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); } else if (onClosureType.isTransferToSavings()) { final Long toSavingsId = command.longValueOfParameterNamed(toSavingsAccountIdParamName); final String transferDescription = command.stringValueOfParameterNamed(transferDescriptionParamName); final SavingsAccount toSavingsAccount = this.depositAccountAssembler.assembleFrom(toSavingsId, DepositAccountType.SAVINGS_DEPOSIT); final boolean isExceptionForBalanceCheck = false; final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(closedDate, transactionAmount, PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, transferDescription, locale, fmt, null, null, null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, account, isRegularTransaction, isExceptionForBalanceCheck); this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); updateAlreadyPostedTransactions(existingTransactionIds, account); } else { final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(), paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); } account.close(user, command, changes); this.savingsAccountRepository.save(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); return savingsTransactionId; } private CalendarInstance getCalendarInstance(final RecurringDepositAccount account, RecurringDepositAccount reinvestedDeposit) { CalendarInstance calendarInstance = null; CalendarInstance parentCalendarInstance = this.calendarInstanceRepository.findByEntityIdAndEntityTypeIdAndCalendarTypeId( account.getId(), CalendarEntityType.SAVINGS.getValue(), CalendarType.COLLECTION.getValue()); if (account.isCalendarInherited()) { calendarInstance = CalendarInstance.from(parentCalendarInstance.getCalendar(), account.getId(), CalendarEntityType.SAVINGS.getValue()); } else { LocalDate calendarStartDate = reinvestedDeposit.depositStartDate(); Calendar parentCalendar = parentCalendarInstance.getCalendar(); final String recurrence = parentCalendar.getRecurrence(); final String title = "recurring_savings_" + reinvestedDeposit.getId(); final Calendar calendar = Calendar.createRepeatingCalendar(title, calendarStartDate, CalendarType.COLLECTION.getValue(), recurrence); calendarInstance = CalendarInstance.from(calendar, reinvestedDeposit.getId(), CalendarEntityType.SAVINGS.getValue()); } if (calendarInstance == null) { final String defaultUserMessage = "No valid recurring details available for recurring depost account creation."; throw new GeneralPlatformDomainRuleException( "error.msg.recurring.deposit.account.cannot.create.no.valid.recurring.details.available", defaultUserMessage, account.clientId()); } return calendarInstance; } private void autoGenerateAccountNumber(final SavingsAccount account) { if (account.isAccountNumberRequiresAutoGeneration()) { final AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository.findByAccountType(EntityAccountType.SAVINGS); account.updateAccountNo(this.accountNumberGenerator.generate(account, accountNumberFormat)); this.savingsAccountRepository.save(account); } } @Transactional @Override public Long handleFDAccountPreMatureClosure(final FixedDepositAccount account, final PaymentDetail paymentDetail, final AppUser user, final JsonCommand command, final Map<String, Object> changes) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); boolean isAccountTransfer = false; boolean isRegularTransaction = false; final boolean isPreMatureClosure = true; final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); // Update account transactionIds for post journal entries. updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); final LocalDate closedDate = command.localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName); final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale); Long savingsTransactionId = null; // post interest account.postPreMaturityInterest(closedDate, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth); final Integer closureTypeValue = command.integerValueOfParameterNamed(DepositsApiConstants.onAccountClosureIdParamName); DepositAccountOnClosureType closureType = DepositAccountOnClosureType.fromInt(closureTypeValue); if (closureType.isTransferToSavings()) { final boolean isExceptionForBalanceCheck = false; final Long toSavingsId = command.longValueOfParameterNamed(toSavingsAccountIdParamName); final String transferDescription = command.stringValueOfParameterNamed(transferDescriptionParamName); final SavingsAccount toSavingsAccount = this.depositAccountAssembler.assembleFrom(toSavingsId, DepositAccountType.SAVINGS_DEPOSIT); final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(closedDate, account.getAccountBalance(), PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, transferDescription, locale, fmt, null, null, null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, account, isRegularTransaction, isExceptionForBalanceCheck); this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); updateAlreadyPostedTransactions(existingTransactionIds, account); } else { final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(), paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); } account.prematureClosure(user, command, changes); this.savingsAccountRepository.save(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); return savingsTransactionId; } @Transactional @Override public Long handleRDAccountPreMatureClosure(final RecurringDepositAccount account, final PaymentDetail paymentDetail, final AppUser user, final JsonCommand command, final Map<String, Object> changes) { final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService .isSavingsInterestPostingAtCurrentPeriodEnd(); final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth(); final boolean postReversals = false; boolean isAccountTransfer = false; final boolean isPreMatureClosure = true; boolean isRegularTransaction = false; final Set<Long> existingTransactionIds = new HashSet<>(); final Set<Long> existingReversedTransactionIds = new HashSet<>(); /*** * Update account transactionIds for post journal entries. */ updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds); final LocalDate closedDate = command.localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName); final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale); Long savingsTransactionId = null; // post interest account.postPreMaturityInterest(closedDate, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postReversals); final Integer closureTypeValue = command.integerValueOfParameterNamed(DepositsApiConstants.onAccountClosureIdParamName); DepositAccountOnClosureType closureType = DepositAccountOnClosureType.fromInt(closureTypeValue); if (closureType.isTransferToSavings()) { final boolean isExceptionForBalanceCheck = false; final Long toSavingsId = command.longValueOfParameterNamed(toSavingsAccountIdParamName); final String transferDescription = command.stringValueOfParameterNamed(transferDescriptionParamName); final SavingsAccount toSavingsAccount = this.depositAccountAssembler.assembleFrom(toSavingsId, DepositAccountType.SAVINGS_DEPOSIT); final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(closedDate, account.getAccountBalance(), PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, transferDescription, locale, fmt, null, null, null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, account, isRegularTransaction, isExceptionForBalanceCheck); this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); updateAlreadyPostedTransactions(existingTransactionIds, account); } else { final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(), paymentDetail, false, isRegularTransaction); savingsTransactionId = withdrawal.getId(); } account.prematureClosure(user, command, changes); this.savingsAccountRepository.save(account); postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer); return savingsTransactionId; } private void updateExistingTransactionsDetails(SavingsAccount account, Set<Long> existingTransactionIds, Set<Long> existingReversedTransactionIds) { existingTransactionIds.addAll(account.findExistingTransactionIds()); existingReversedTransactionIds.addAll(account.findExistingReversedTransactionIds()); } private void postJournalEntries(final SavingsAccount savingsAccount, final Set<Long> existingTransactionIds, final Set<Long> existingReversedTransactionIds, boolean isAccountTransfer) { final boolean backdatedTxnsAllowedTill = false; final Map<String, Object> accountingBridgeData = savingsAccount.deriveAccountingBridgeData(savingsAccount.getCurrency().getCode(), existingTransactionIds, existingReversedTransactionIds, isAccountTransfer, backdatedTxnsAllowedTill); this.journalEntryWritePlatformService.createJournalEntriesForSavings(accountingBridgeData); } private void updateAlreadyPostedTransactions(final Set<Long> existingTransactionIds, final SavingsAccount savingsAccount) { List<SavingsAccountTransaction> transactions = savingsAccount.getTransactions(); int size = transactions.size(); for (int i = size - 1;; i--) { SavingsAccountTransaction transaction = transactions.get(i); if (transaction.isWithdrawal() || transaction.isWithdrawalFee()) { existingTransactionIds.add(transaction.getId()); } else { break; } } } }
google/cel-java
35,514
bundle/src/test/java/dev/cel/bundle/CelEnvironmentYamlParserTest.java
// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package dev.cel.bundle; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertThrows; import com.google.common.base.Ascii; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.io.Resources; import com.google.rpc.context.AttributeContext; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; import dev.cel.bundle.CelEnvironment.ExtensionConfig; import dev.cel.bundle.CelEnvironment.FunctionDecl; import dev.cel.bundle.CelEnvironment.LibrarySubset; import dev.cel.bundle.CelEnvironment.LibrarySubset.FunctionSelector; import dev.cel.bundle.CelEnvironment.OverloadDecl; import dev.cel.bundle.CelEnvironment.TypeDecl; import dev.cel.bundle.CelEnvironment.VariableDecl; import dev.cel.common.CelAbstractSyntaxTree; import dev.cel.common.CelOptions; import dev.cel.common.CelSource; import dev.cel.common.ast.CelExpr; import dev.cel.common.types.SimpleType; import dev.cel.parser.CelUnparserFactory; import dev.cel.runtime.CelEvaluationListener; import dev.cel.runtime.CelLateFunctionBindings; import dev.cel.runtime.CelFunctionBinding; import java.io.IOException; import java.net.URL; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(TestParameterInjector.class) public final class CelEnvironmentYamlParserTest { private static final Cel CEL_WITH_MESSAGE_TYPES = CelFactory.standardCelBuilder() .addMessageTypes(AttributeContext.Request.getDescriptor()) .build(); private static final CelEnvironmentYamlParser ENVIRONMENT_PARSER = CelEnvironmentYamlParser.newInstance(); @Test public void environment_setEmpty() throws Exception { assertThrows(CelEnvironmentException.class, () -> ENVIRONMENT_PARSER.parse("")); } @Test public void environment_setBasicProperties() throws Exception { String yamlConfig = "name: hello\n" + "description: empty\n" + "container: pb.pkg\n"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .setName("hello") .setDescription("empty") .setContainer("pb.pkg") .build()); } @Test public void environment_setExtensions() throws Exception { String yamlConfig = "extensions:\n" + " - name: 'bindings'\n" + " - name: 'encoders'\n" + " - name: 'lists'\n" + " - name: 'math'\n" + " - name: 'optional'\n" + " - name: 'protos'\n" + " - name: 'sets'\n" + " - name: 'strings'\n" + " version: 1"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .addExtensions( ImmutableSet.of( ExtensionConfig.of("bindings"), ExtensionConfig.of("encoders"), ExtensionConfig.of("lists"), ExtensionConfig.of("math"), ExtensionConfig.of("optional"), ExtensionConfig.of("protos"), ExtensionConfig.of("sets"), ExtensionConfig.of("strings", 1))) .build()); assertThat(environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)).isNotNull(); } @Test public void environment_setExtensionVersionToLatest() throws Exception { String yamlConfig = "extensions:\n" // + " - name: 'bindings'\n" // + " version: latest"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .addExtensions(ImmutableSet.of(ExtensionConfig.of("bindings", Integer.MAX_VALUE))) .build()); assertThat(environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)).isNotNull(); } @Test public void environment_setExtensionVersionToInvalidValue() throws Exception { String yamlConfig = "extensions:\n" // + " - name: 'bindings'\n" // + " version: invalid"; CelEnvironmentException e = assertThrows(CelEnvironmentException.class, () -> ENVIRONMENT_PARSER.parse(yamlConfig)); assertThat(e) .hasMessageThat() .contains( "ERROR: <input>:3:5: Unsupported version tag: version\n" + " | version: invalid\n" + " | ....^"); } @Test public void environment_setFunctions() throws Exception { String yamlConfig = "functions:\n" + " - name: 'coalesce'\n" + " overloads:\n" + " - id: 'null_coalesce_int'\n" + " target:\n" + " type_name: 'null_type'\n" + " args:\n" + " - type_name: 'int'\n" + " return:\n" + " type_name: 'int'\n" + " - id: 'coalesce_null_int'\n" + " args:\n" + " - type_name: 'null_type'\n" + " - type_name: 'int'\n" + " return:\n" + " type_name: 'int' \n" + " - id: 'int_coalesce_int'\n" + " target: \n" + " type_name: 'int'\n" + " args:\n" + " - type_name: 'int'\n" + " return: \n" + " type_name: 'int'\n" + " - id: 'optional_T_coalesce_T'\n" + " target: \n" + " type_name: 'optional_type'\n" + " params:\n" + " - type_name: 'T'\n" + " is_type_param: true\n" + " args:\n" + " - type_name: 'T'\n" + " is_type_param: true\n" + " return: \n" + " type_name: 'T'\n" + " is_type_param: true"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .setFunctions( ImmutableSet.of( FunctionDecl.create( "coalesce", ImmutableSet.of( OverloadDecl.newBuilder() .setId("null_coalesce_int") .setTarget(TypeDecl.create("null_type")) .addArguments(TypeDecl.create("int")) .setReturnType(TypeDecl.create("int")) .build(), OverloadDecl.newBuilder() .setId("coalesce_null_int") .addArguments( TypeDecl.create("null_type"), TypeDecl.create("int")) .setReturnType(TypeDecl.create("int")) .build(), OverloadDecl.newBuilder() .setId("int_coalesce_int") .setTarget(TypeDecl.create("int")) .addArguments(TypeDecl.create("int")) .setReturnType(TypeDecl.create("int")) .build(), OverloadDecl.newBuilder() .setId("optional_T_coalesce_T") .setTarget( TypeDecl.newBuilder() .setName("optional_type") .addParams( TypeDecl.newBuilder() .setName("T") .setIsTypeParam(true) .build()) .build()) .addArguments( TypeDecl.newBuilder() .setName("T") .setIsTypeParam(true) .build()) .setReturnType( TypeDecl.newBuilder() .setName("T") .setIsTypeParam(true) .build()) .build())))) .build()); assertThat(environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)).isNotNull(); } @Test public void environment_setListVariable() throws Exception { String yamlConfig = "variables:\n" + "- name: 'request'\n" + " type_name: 'list'\n" + " params:\n" + " - type_name: 'string'"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .setVariables( ImmutableSet.of( VariableDecl.create( "request", TypeDecl.newBuilder() .setName("list") .addParams(TypeDecl.create("string")) .build()))) .build()); } @Test public void environment_setMapVariable() throws Exception { String yamlConfig = "variables:\n" + "- name: 'request'\n" + " type:\n" + " type_name: 'map'\n" + " params:\n" + " - type_name: 'string'\n" + " - type_name: 'dyn'"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .setVariables( ImmutableSet.of( VariableDecl.create( "request", TypeDecl.newBuilder() .setName("map") .addParams(TypeDecl.create("string"), TypeDecl.create("dyn")) .build()))) .build()); assertThat(environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)).isNotNull(); } @Test public void environment_setMessageVariable() throws Exception { String yamlConfig = "variables:\n" + "- name: 'request'\n" + " type:\n" + " type_name: 'google.rpc.context.AttributeContext.Request'"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .setVariables( ImmutableSet.of( VariableDecl.create( "request", TypeDecl.create("google.rpc.context.AttributeContext.Request")))) .build()); assertThat(environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)).isNotNull(); } @Test public void environment_setContainer() throws Exception { String yamlConfig = "container: google.rpc.context\n" + "variables:\n" + "- name: 'request'\n" + " type:\n" + " type_name: 'google.rpc.context.AttributeContext.Request'"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setContainer("google.rpc.context") .setSource(environment.source().get()) .setVariables( ImmutableSet.of( VariableDecl.create( "request", TypeDecl.create("google.rpc.context.AttributeContext.Request")))) .build()); assertThat(environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)).isNotNull(); } @Test public void environment_withInlinedVariableDecl() throws Exception { String yamlConfig = "variables:\n" + "- name: 'request'\n" + " type_name: 'google.rpc.context.AttributeContext.Request'\n" + "- name: 'map_var'\n" + " type_name: 'map'\n" + " params:\n" + " - type_name: 'string'\n" + " - type_name: 'string'"; CelEnvironment environment = ENVIRONMENT_PARSER.parse(yamlConfig); assertThat(environment) .isEqualTo( CelEnvironment.newBuilder() .setSource(environment.source().get()) .setVariables( ImmutableSet.of( VariableDecl.create( "request", TypeDecl.create("google.rpc.context.AttributeContext.Request")), VariableDecl.create( "map_var", TypeDecl.newBuilder() .setName("map") .addParams(TypeDecl.create("string"), TypeDecl.create("string")) .build()))) .build()); assertThat(environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)).isNotNull(); } @Test public void environment_parseErrors(@TestParameter EnvironmentParseErrorTestcase testCase) { CelEnvironmentException e = assertThrows( CelEnvironmentException.class, () -> ENVIRONMENT_PARSER.parse(testCase.yamlConfig)); assertThat(e).hasMessageThat().isEqualTo(testCase.expectedErrorMessage); } @Test public void environment_extendErrors(@TestParameter EnvironmentExtendErrorTestCase testCase) throws Exception { CelEnvironment environment = ENVIRONMENT_PARSER.parse(testCase.yamlConfig); CelEnvironmentException e = assertThrows( CelEnvironmentException.class, () -> environment.extend(CEL_WITH_MESSAGE_TYPES, CelOptions.DEFAULT)); assertThat(e).hasMessageThat().isEqualTo(testCase.expectedErrorMessage); } // Note: dangling comments in expressions below is to retain the newlines by preventing auto // formatter from compressing them in a single line. private enum EnvironmentParseErrorTestcase { MALFORMED_YAML_DOCUMENT( "a:\na", "YAML document is malformed: while scanning a simple key\n" + " in 'reader', line 2, column 1:\n" + " a\n" + " ^\n" + "could not find expected ':'\n" + " in 'reader', line 2, column 2:\n" + " a\n" + " ^\n"), ILLEGAL_YAML_TYPE_CONFIG_KEY( "1: test", "ERROR: <input>:1:1: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:str !txt]\n" + " | 1: test\n" + " | ^"), ILLEGAL_YAML_TYPE_CONFIG_VALUE( "test: 1", "ERROR: <input>:1:1: Unknown config tag: test\n" + " | test: 1\n" + " | ^"), ILLEGAL_YAML_TYPE_VARIABLE_LIST( "variables: 1", "ERROR: <input>:1:12: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:seq]\n" + " | variables: 1\n" + " | ...........^"), ILLEGAL_YAML_TYPE_VARIABLE_VALUE( "variables:\n - 1", "ERROR: <input>:2:4: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:map]\n" + " | - 1\n" + " | ...^"), ILLEGAL_YAML_TYPE_FUNCTION_LIST( "functions: 1", "ERROR: <input>:1:12: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:seq]\n" + " | functions: 1\n" + " | ...........^"), ILLEGAL_YAML_TYPE_FUNCTION_VALUE( "functions:\n - 1", "ERROR: <input>:2:4: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:map]\n" + " | - 1\n" + " | ...^"), ILLEGAL_YAML_TYPE_OVERLOAD_LIST( "functions:\n" // + " - name: foo\n" // + " overloads: 1", "ERROR: <input>:3:15: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:seq]\n" + " | overloads: 1\n" + " | ..............^"), ILLEGAL_YAML_TYPE_OVERLOAD_VALUE( "functions:\n" // + " - name: foo\n" // + " overloads:\n" // + " - 2", "ERROR: <input>:4:7: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:map]\n" + " | - 2\n" + " | ......^"), ILLEGAL_YAML_TYPE_OVERLOAD_VALUE_MAP_KEY( "functions:\n" // + " - name: foo\n" // + " overloads:\n" // + " - 2: test", "ERROR: <input>:4:9: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:str !txt]\n" + " | - 2: test\n" + " | ........^\n" + "ERROR: <input>:4:9: Missing required attribute(s): id, return\n" + " | - 2: test\n" + " | ........^"), ILLEGAL_YAML_TYPE_EXTENSION_LIST( "extensions: 1", "ERROR: <input>:1:13: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:seq]\n" + " | extensions: 1\n" + " | ............^"), ILLEGAL_YAML_TYPE_EXTENSION_VALUE( "extensions:\n - 1", "ERROR: <input>:2:4: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:map]\n" + " | - 1\n" + " | ...^"), ILLEGAL_YAML_TYPE_TYPE_DECL( "variables:\n" // + " - name: foo\n" // + " type: 1", "ERROR: <input>:3:10: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:map]\n" + " | type: 1\n" + " | .........^"), ILLEGAL_YAML_TYPE_TYPE_VALUE( "variables:\n" + " - name: foo\n" + " type:\n" + " type_name: bar\n" + " 1: hello", "ERROR: <input>:5:6: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:str !txt]\n" + " | 1: hello\n" + " | .....^"), ILLEGAL_YAML_TYPE_TYPE_PARAMS_LIST( "variables:\n" + " - name: foo\n" + " type:\n" + " type_name: bar\n" + " params: 1", "ERROR: <input>:5:14: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:seq]\n" + " | params: 1\n" + " | .............^"), ILLEGAL_YAML_TYPE_WITH_INLINED_TYPE_TAGS( "variables:\n" + " - name: foo\n" + " type_name: bar\n" + " type:\n" + " type_name: qux\n", "ERROR: <input>:4:4: 'type' tag cannot be used together with inlined 'type_name'," + " 'is_type_param' or 'params': type\n" + " | type:\n" + " | ...^"), ILLEGAL_YAML_INLINED_TYPE_VALUE( "variables:\n" // + " - name: foo\n" // + " type_name: 1\n", "ERROR: <input>:3:15: Got yaml node type tag:yaml.org,2002:int, wanted type(s)" + " [tag:yaml.org,2002:str !txt]\n" + " | type_name: 1\n" + " | ..............^"), UNSUPPORTED_CONFIG_TAG( "unsupported: test", "ERROR: <input>:1:1: Unknown config tag: unsupported\n" + " | unsupported: test\n" + " | ^"), UNSUPPORTED_EXTENSION_TAG( "extensions:\n" // + " - name: foo\n" // + " unsupported: test", "ERROR: <input>:3:5: Unsupported extension tag: unsupported\n" + " | unsupported: test\n" + " | ....^"), UNSUPPORTED_TYPE_DECL_TAG( "variables:\n" + "- name: foo\n" + " type:\n" + " type_name: bar\n" + " unsupported: hello", "ERROR: <input>:5:6: Unsupported type decl tag: unsupported\n" + " | unsupported: hello\n" + " | .....^"), MISSING_VARIABLE_PROPERTIES( "variables:\n - illegal: 2", "ERROR: <input>:2:4: Unsupported variable tag: illegal\n" + " | - illegal: 2\n" + " | ...^\n" + "ERROR: <input>:2:4: Missing required attribute(s): name, type\n" + " | - illegal: 2\n" + " | ...^"), MISSING_OVERLOAD_RETURN( "functions:\n" + " - name: 'missing_return'\n" + " overloads:\n" + " - id: 'zero_arity'\n", "ERROR: <input>:4:9: Missing required attribute(s): return\n" + " | - id: 'zero_arity'\n" + " | ........^"), MISSING_FUNCTION_NAME( "functions:\n" + " - overloads:\n" + " - id: 'foo'\n" + " return:\n" + " type_name: 'string'\n", "ERROR: <input>:2:5: Missing required attribute(s): name\n" + " | - overloads:\n" + " | ....^"), MISSING_OVERLOAD( "functions:\n" + " - name: 'missing_overload'\n", "ERROR: <input>:2:5: Missing required attribute(s): overloads\n" + " | - name: 'missing_overload'\n" + " | ....^"), MISSING_EXTENSION_NAME( "extensions:\n" + "- version: 0", "ERROR: <input>:2:3: Missing required attribute(s): name\n" + " | - version: 0\n" + " | ..^"), ILLEGAL_LIBRARY_SUBSET_TAG( "name: 'test_suite_name'\n" + "stdlib:\n" + " unknown_tag: 'test_value'\n", "ERROR: <input>:3:3: Unsupported library subset tag: unknown_tag\n" + " | unknown_tag: 'test_value'\n" + " | ..^"), ILLEGAL_LIBRARY_SUBSET_FUNCTION_SELECTOR_TAG( "name: 'test_suite_name'\n" + "stdlib:\n" + " include_functions:\n" + " - name: 'test_function'\n" + " unknown_tag: 'test_value'\n", "ERROR: <input>:5:7: Unsupported function selector tag: unknown_tag\n" + " | unknown_tag: 'test_value'\n" + " | ......^"), MISSING_LIBRARY_SUBSET_FUNCTION_SELECTOR_NAME( "name: 'test_suite_name'\n" + "stdlib:\n" + " include_functions:\n" + " - overloads:\n" + " - id: add_bytes\n", "ERROR: <input>:4:7: Missing required attribute(s): name\n" + " | - overloads:\n" + " | ......^"), ILLEGAL_LIBRARY_SUBSET_OVERLOAD_SELECTOR_TAG( "name: 'test_suite_name'\n" + "stdlib:\n" + " include_functions:\n" + " - name: _+_\n" + " overloads:\n" + " - id: test_overload\n" + " unknown_tag: 'test_value'\n", "ERROR: <input>:7:11: Unsupported overload selector tag: unknown_tag\n" + " | unknown_tag: 'test_value'\n" + " | ..........^"), ; private final String yamlConfig; private final String expectedErrorMessage; EnvironmentParseErrorTestcase(String yamlConfig, String expectedErrorMessage) { this.yamlConfig = yamlConfig; this.expectedErrorMessage = expectedErrorMessage; } } private enum EnvironmentExtendErrorTestCase { BAD_EXTENSION("extensions:\n" + " - name: 'bad_name'", "Unrecognized extension: bad_name"), BAD_TYPE( "variables:\n" + "- name: 'bad_type'\n" + " type:\n" + " type_name: 'strings'", "Undefined type name: strings"), BAD_LIST( "variables:\n" + " - name: 'bad_list'\n" + " type:\n" + " type_name: 'list'", "List type has unexpected param count: 0"), BAD_MAP( "variables:\n" + " - name: 'bad_map'\n" + " type:\n" + " type_name: 'map'\n" + " params:\n" + " - type_name: 'string'", "Map type has unexpected param count: 1"), BAD_LIST_TYPE_PARAM( "variables:\n" + " - name: 'bad_list_type_param'\n" + " type:\n" + " type_name: 'list'\n" + " params:\n" + " - type_name: 'number'", "Undefined type name: number"), BAD_MAP_TYPE_PARAM( "variables:\n" + " - name: 'bad_map_type_param'\n" + " type:\n" + " type_name: 'map'\n" + " params:\n" + " - type_name: 'string'\n" + " - type_name: 'optional'", "Undefined type name: optional"), BAD_RETURN( "functions:\n" + " - name: 'bad_return'\n" + " overloads:\n" + " - id: 'zero_arity'\n" + " return:\n" + " type_name: 'mystery'", "Undefined type name: mystery"), BAD_OVERLOAD_TARGET( "functions:\n" + " - name: 'bad_target'\n" + " overloads:\n" + " - id: 'unary_member'\n" + " target:\n" + " type_name: 'unknown'\n" + " return:\n" + " type_name: 'null_type'", "Undefined type name: unknown"), BAD_OVERLOAD_ARG( "functions:\n" + " - name: 'bad_arg'\n" + " overloads:\n" + " - id: 'unary_global'\n" + " args:\n" + " - type_name: 'unknown'\n" + " return:\n" + " type_name: 'null_type'", "Undefined type name: unknown"), ; private final String yamlConfig; private final String expectedErrorMessage; EnvironmentExtendErrorTestCase(String yamlConfig, String expectedErrorMessage) { this.yamlConfig = yamlConfig; this.expectedErrorMessage = expectedErrorMessage; } } @SuppressWarnings("ImmutableEnumChecker") // Test only private enum EnvironmentYamlResourceTestCase { EXTENDED_ENV( "environment/extended_env.yaml", CelEnvironment.newBuilder() .setName("extended-env") .setContainer("cel.expr") .addExtensions( ImmutableSet.of( ExtensionConfig.of("optional", 2), ExtensionConfig.of("math", Integer.MAX_VALUE))) .setVariables( VariableDecl.newBuilder() .setName("msg") .setType(TypeDecl.create("cel.expr.conformance.proto3.TestAllTypes")) .build()) .setFunctions( FunctionDecl.create( "isEmpty", ImmutableSet.of( OverloadDecl.newBuilder() .setId("wrapper_string_isEmpty") .setTarget(TypeDecl.create("google.protobuf.StringValue")) .setReturnType(TypeDecl.create("bool")) .build(), OverloadDecl.newBuilder() .setId("list_isEmpty") .setTarget( TypeDecl.newBuilder() .setName("list") .addParams( TypeDecl.newBuilder() .setName("T") .setIsTypeParam(true) .build()) .build()) .setReturnType(TypeDecl.create("bool")) .build()))) .build()), LIBRARY_SUBSET_ENV( "environment/subset_env.yaml", CelEnvironment.newBuilder() .setName("subset-env") .setStandardLibrarySubset( LibrarySubset.newBuilder() .setDisabled(false) .setExcludedMacros(ImmutableSet.of("map", "filter")) .setExcludedFunctions( ImmutableSet.of( FunctionSelector.create( "_+_", ImmutableSet.of("add_bytes", "add_list", "add_string")), FunctionSelector.create("matches", ImmutableSet.of()), FunctionSelector.create( "timestamp", ImmutableSet.of("string_to_timestamp")), FunctionSelector.create( "duration", ImmutableSet.of("string_to_duration")))) .build()) .setVariables( VariableDecl.create("x", TypeDecl.create("int")), VariableDecl.create("y", TypeDecl.create("double")), VariableDecl.create("z", TypeDecl.create("uint"))) .build()), ; private final String yamlFileContent; private final CelEnvironment expectedEnvironment; EnvironmentYamlResourceTestCase(String yamlResourcePath, CelEnvironment expectedEnvironment) { try { this.yamlFileContent = readFile(yamlResourcePath); } catch (IOException e) { throw new RuntimeException(e); } this.expectedEnvironment = expectedEnvironment; } } @Test public void environment_withYamlResource(@TestParameter EnvironmentYamlResourceTestCase testCase) throws Exception { CelEnvironment environment = ENVIRONMENT_PARSER.parse(testCase.yamlFileContent); // Empty out the parsed yaml source, as it's not relevant in the assertion here, and that it's // only obtainable through the yaml parser. environment = environment.toBuilder().setSource(Optional.empty()).build(); assertThat(environment).isEqualTo(testCase.expectedEnvironment); } @Test public void lateBoundFunction_evaluate_callExpr() throws Exception { String configSource = "name: late_bound_function_config\n" + "functions:\n" + " - name: 'test'\n" + " overloads:\n" + " - id: 'test_bool'\n" + " args:\n" + " - type_name: 'bool'\n" + " return:\n" + " type_name: 'bool'"; CelEnvironment celEnvironment = ENVIRONMENT_PARSER.parse(configSource); Cel celDetails = CelFactory.standardCelBuilder() .addVar("a", SimpleType.INT) .addVar("b", SimpleType.INT) .addVar("c", SimpleType.INT) .build(); Cel cel = celEnvironment.extend(celDetails, CelOptions.DEFAULT); CelAbstractSyntaxTree ast = cel.compile("a < 0 && b < 0 && c < 0 && test(a<0)").getAst(); CelLateFunctionBindings bindings = CelLateFunctionBindings.from( CelFunctionBinding.from("test_bool", Boolean.class, result -> result)); boolean result = (boolean) cel.createProgram(ast).eval(ImmutableMap.of("a", -1, "b", -1, "c", -4), bindings); assertThat(result).isTrue(); } @Test public void lateBoundFunction_trace_callExpr_identifyFalseBranch() throws Exception { AtomicReference<CelExpr> capturedExpr = new AtomicReference<>(); CelEvaluationListener listener = (expr, res) -> { if (res instanceof Boolean && !(boolean) res && capturedExpr.get() == null) { capturedExpr.set(expr); } }; String configSource = "name: late_bound_function_config\n" + "functions:\n" + " - name: 'test'\n" + " overloads:\n" + " - id: 'test_bool'\n" + " args:\n" + " - type_name: 'bool'\n" + " return:\n" + " type_name: 'bool'"; CelEnvironment celEnvironment = ENVIRONMENT_PARSER.parse(configSource); Cel celDetails = CelFactory.standardCelBuilder() .addVar("a", SimpleType.INT) .addVar("b", SimpleType.INT) .addVar("c", SimpleType.INT) .build(); Cel cel = celEnvironment.extend(celDetails, CelOptions.DEFAULT); CelAbstractSyntaxTree ast = cel.compile("a < 0 && b < 0 && c < 0 && test(a<0)").getAst(); CelLateFunctionBindings bindings = CelLateFunctionBindings.from( CelFunctionBinding.from("test_bool", Boolean.class, result -> result)); boolean result = (boolean) cel.createProgram(ast) .trace(ImmutableMap.of("a", -1, "b", 1, "c", -4), bindings, listener); assertThat(result).isFalse(); // Demonstrate that "b < 0" is what caused the expression to be false CelAbstractSyntaxTree subtree = CelAbstractSyntaxTree.newParsedAst(capturedExpr.get(), CelSource.newBuilder().build()); assertThat(CelUnparserFactory.newUnparser().unparse(subtree)).isEqualTo("b < 0"); } private static String readFile(String path) throws IOException { URL url = Resources.getResource(Ascii.toLowerCase(path)); return Resources.toString(url, UTF_8); } }
googleapis/google-cloud-java
36,361
java-shopping-css/proto-google-shopping-css-v1/src/main/java/com/google/shopping/css/v1/ListChildAccountsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/shopping/css/v1/accounts.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.css.v1; /** * * * <pre> * Response message for the `ListChildAccounts` method. * </pre> * * Protobuf type {@code google.shopping.css.v1.ListChildAccountsResponse} */ public final class ListChildAccountsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.css.v1.ListChildAccountsResponse) ListChildAccountsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListChildAccountsResponse.newBuilder() to construct. private ListChildAccountsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListChildAccountsResponse() { accounts_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListChildAccountsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.css.v1.AccountsProto .internal_static_google_shopping_css_v1_ListChildAccountsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.css.v1.AccountsProto .internal_static_google_shopping_css_v1_ListChildAccountsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.css.v1.ListChildAccountsResponse.class, com.google.shopping.css.v1.ListChildAccountsResponse.Builder.class); } public static final int ACCOUNTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.shopping.css.v1.Account> accounts_; /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ @java.lang.Override public java.util.List<com.google.shopping.css.v1.Account> getAccountsList() { return accounts_; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.shopping.css.v1.AccountOrBuilder> getAccountsOrBuilderList() { return accounts_; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ @java.lang.Override public int getAccountsCount() { return accounts_.size(); } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ @java.lang.Override public com.google.shopping.css.v1.Account getAccounts(int index) { return accounts_.get(index); } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ @java.lang.Override public com.google.shopping.css.v1.AccountOrBuilder getAccountsOrBuilder(int index) { return accounts_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < accounts_.size(); i++) { output.writeMessage(1, accounts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < accounts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, accounts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.shopping.css.v1.ListChildAccountsResponse)) { return super.equals(obj); } com.google.shopping.css.v1.ListChildAccountsResponse other = (com.google.shopping.css.v1.ListChildAccountsResponse) obj; if (!getAccountsList().equals(other.getAccountsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getAccountsCount() > 0) { hash = (37 * hash) + ACCOUNTS_FIELD_NUMBER; hash = (53 * hash) + getAccountsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.css.v1.ListChildAccountsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.shopping.css.v1.ListChildAccountsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for the `ListChildAccounts` method. * </pre> * * Protobuf type {@code google.shopping.css.v1.ListChildAccountsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.css.v1.ListChildAccountsResponse) com.google.shopping.css.v1.ListChildAccountsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.css.v1.AccountsProto .internal_static_google_shopping_css_v1_ListChildAccountsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.css.v1.AccountsProto .internal_static_google_shopping_css_v1_ListChildAccountsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.css.v1.ListChildAccountsResponse.class, com.google.shopping.css.v1.ListChildAccountsResponse.Builder.class); } // Construct using com.google.shopping.css.v1.ListChildAccountsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (accountsBuilder_ == null) { accounts_ = java.util.Collections.emptyList(); } else { accounts_ = null; accountsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.css.v1.AccountsProto .internal_static_google_shopping_css_v1_ListChildAccountsResponse_descriptor; } @java.lang.Override public com.google.shopping.css.v1.ListChildAccountsResponse getDefaultInstanceForType() { return com.google.shopping.css.v1.ListChildAccountsResponse.getDefaultInstance(); } @java.lang.Override public com.google.shopping.css.v1.ListChildAccountsResponse build() { com.google.shopping.css.v1.ListChildAccountsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.css.v1.ListChildAccountsResponse buildPartial() { com.google.shopping.css.v1.ListChildAccountsResponse result = new com.google.shopping.css.v1.ListChildAccountsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.shopping.css.v1.ListChildAccountsResponse result) { if (accountsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { accounts_ = java.util.Collections.unmodifiableList(accounts_); bitField0_ = (bitField0_ & ~0x00000001); } result.accounts_ = accounts_; } else { result.accounts_ = accountsBuilder_.build(); } } private void buildPartial0(com.google.shopping.css.v1.ListChildAccountsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.shopping.css.v1.ListChildAccountsResponse) { return mergeFrom((com.google.shopping.css.v1.ListChildAccountsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.shopping.css.v1.ListChildAccountsResponse other) { if (other == com.google.shopping.css.v1.ListChildAccountsResponse.getDefaultInstance()) return this; if (accountsBuilder_ == null) { if (!other.accounts_.isEmpty()) { if (accounts_.isEmpty()) { accounts_ = other.accounts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureAccountsIsMutable(); accounts_.addAll(other.accounts_); } onChanged(); } } else { if (!other.accounts_.isEmpty()) { if (accountsBuilder_.isEmpty()) { accountsBuilder_.dispose(); accountsBuilder_ = null; accounts_ = other.accounts_; bitField0_ = (bitField0_ & ~0x00000001); accountsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getAccountsFieldBuilder() : null; } else { accountsBuilder_.addAllMessages(other.accounts_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.shopping.css.v1.Account m = input.readMessage( com.google.shopping.css.v1.Account.parser(), extensionRegistry); if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(m); } else { accountsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.shopping.css.v1.Account> accounts_ = java.util.Collections.emptyList(); private void ensureAccountsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { accounts_ = new java.util.ArrayList<com.google.shopping.css.v1.Account>(accounts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.css.v1.Account, com.google.shopping.css.v1.Account.Builder, com.google.shopping.css.v1.AccountOrBuilder> accountsBuilder_; /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public java.util.List<com.google.shopping.css.v1.Account> getAccountsList() { if (accountsBuilder_ == null) { return java.util.Collections.unmodifiableList(accounts_); } else { return accountsBuilder_.getMessageList(); } } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public int getAccountsCount() { if (accountsBuilder_ == null) { return accounts_.size(); } else { return accountsBuilder_.getCount(); } } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public com.google.shopping.css.v1.Account getAccounts(int index) { if (accountsBuilder_ == null) { return accounts_.get(index); } else { return accountsBuilder_.getMessage(index); } } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder setAccounts(int index, com.google.shopping.css.v1.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.set(index, value); onChanged(); } else { accountsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder setAccounts( int index, com.google.shopping.css.v1.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.set(index, builderForValue.build()); onChanged(); } else { accountsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder addAccounts(com.google.shopping.css.v1.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.add(value); onChanged(); } else { accountsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder addAccounts(int index, com.google.shopping.css.v1.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.add(index, value); onChanged(); } else { accountsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder addAccounts(com.google.shopping.css.v1.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(builderForValue.build()); onChanged(); } else { accountsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder addAccounts( int index, com.google.shopping.css.v1.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(index, builderForValue.build()); onChanged(); } else { accountsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder addAllAccounts( java.lang.Iterable<? extends com.google.shopping.css.v1.Account> values) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, accounts_); onChanged(); } else { accountsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder clearAccounts() { if (accountsBuilder_ == null) { accounts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { accountsBuilder_.clear(); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public Builder removeAccounts(int index) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.remove(index); onChanged(); } else { accountsBuilder_.remove(index); } return this; } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public com.google.shopping.css.v1.Account.Builder getAccountsBuilder(int index) { return getAccountsFieldBuilder().getBuilder(index); } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public com.google.shopping.css.v1.AccountOrBuilder getAccountsOrBuilder(int index) { if (accountsBuilder_ == null) { return accounts_.get(index); } else { return accountsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public java.util.List<? extends com.google.shopping.css.v1.AccountOrBuilder> getAccountsOrBuilderList() { if (accountsBuilder_ != null) { return accountsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(accounts_); } } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public com.google.shopping.css.v1.Account.Builder addAccountsBuilder() { return getAccountsFieldBuilder() .addBuilder(com.google.shopping.css.v1.Account.getDefaultInstance()); } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public com.google.shopping.css.v1.Account.Builder addAccountsBuilder(int index) { return getAccountsFieldBuilder() .addBuilder(index, com.google.shopping.css.v1.Account.getDefaultInstance()); } /** * * * <pre> * The CSS/MC accounts returned for the specified CSS parent account. * </pre> * * <code>repeated .google.shopping.css.v1.Account accounts = 1;</code> */ public java.util.List<com.google.shopping.css.v1.Account.Builder> getAccountsBuilderList() { return getAccountsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.css.v1.Account, com.google.shopping.css.v1.Account.Builder, com.google.shopping.css.v1.AccountOrBuilder> getAccountsFieldBuilder() { if (accountsBuilder_ == null) { accountsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.css.v1.Account, com.google.shopping.css.v1.Account.Builder, com.google.shopping.css.v1.AccountOrBuilder>( accounts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); accounts_ = null; } return accountsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.shopping.css.v1.ListChildAccountsResponse) } // @@protoc_insertion_point(class_scope:google.shopping.css.v1.ListChildAccountsResponse) private static final com.google.shopping.css.v1.ListChildAccountsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.css.v1.ListChildAccountsResponse(); } public static com.google.shopping.css.v1.ListChildAccountsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListChildAccountsResponse> PARSER = new com.google.protobuf.AbstractParser<ListChildAccountsResponse>() { @java.lang.Override public ListChildAccountsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListChildAccountsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListChildAccountsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.css.v1.ListChildAccountsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,385
java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/ExportIntentsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/cx/v3/intent.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.cx.v3; /** * * * <pre> * The response message for * [Intents.ExportIntents][google.cloud.dialogflow.cx.v3.Intents.ExportIntents]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3.ExportIntentsResponse} */ public final class ExportIntentsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3.ExportIntentsResponse) ExportIntentsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ExportIntentsResponse.newBuilder() to construct. private ExportIntentsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExportIntentsResponse() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ExportIntentsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3.IntentProto .internal_static_google_cloud_dialogflow_cx_v3_ExportIntentsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3.IntentProto .internal_static_google_cloud_dialogflow_cx_v3_ExportIntentsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse.class, com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse.Builder.class); } private int intentsCase_ = 0; @SuppressWarnings("serial") private java.lang.Object intents_; public enum IntentsCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { INTENTS_URI(1), INTENTS_CONTENT(2), INTENTS_NOT_SET(0); private final int value; private IntentsCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static IntentsCase valueOf(int value) { return forNumber(value); } public static IntentsCase forNumber(int value) { switch (value) { case 1: return INTENTS_URI; case 2: return INTENTS_CONTENT; case 0: return INTENTS_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public IntentsCase getIntentsCase() { return IntentsCase.forNumber(intentsCase_); } public static final int INTENTS_URI_FIELD_NUMBER = 1; /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @return Whether the intentsUri field is set. */ public boolean hasIntentsUri() { return intentsCase_ == 1; } /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @return The intentsUri. */ public java.lang.String getIntentsUri() { java.lang.Object ref = ""; if (intentsCase_ == 1) { ref = intents_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (intentsCase_ == 1) { intents_ = s; } return s; } } /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @return The bytes for intentsUri. */ public com.google.protobuf.ByteString getIntentsUriBytes() { java.lang.Object ref = ""; if (intentsCase_ == 1) { ref = intents_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (intentsCase_ == 1) { intents_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int INTENTS_CONTENT_FIELD_NUMBER = 2; /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> * * @return Whether the intentsContent field is set. */ @java.lang.Override public boolean hasIntentsContent() { return intentsCase_ == 2; } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> * * @return The intentsContent. */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3.InlineDestination getIntentsContent() { if (intentsCase_ == 2) { return (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_; } return com.google.cloud.dialogflow.cx.v3.InlineDestination.getDefaultInstance(); } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3.InlineDestinationOrBuilder getIntentsContentOrBuilder() { if (intentsCase_ == 2) { return (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_; } return com.google.cloud.dialogflow.cx.v3.InlineDestination.getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (intentsCase_ == 1) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, intents_); } if (intentsCase_ == 2) { output.writeMessage(2, (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (intentsCase_ == 1) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, intents_); } if (intentsCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse other = (com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse) obj; if (!getIntentsCase().equals(other.getIntentsCase())) return false; switch (intentsCase_) { case 1: if (!getIntentsUri().equals(other.getIntentsUri())) return false; break; case 2: if (!getIntentsContent().equals(other.getIntentsContent())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); switch (intentsCase_) { case 1: hash = (37 * hash) + INTENTS_URI_FIELD_NUMBER; hash = (53 * hash) + getIntentsUri().hashCode(); break; case 2: hash = (37 * hash) + INTENTS_CONTENT_FIELD_NUMBER; hash = (53 * hash) + getIntentsContent().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response message for * [Intents.ExportIntents][google.cloud.dialogflow.cx.v3.Intents.ExportIntents]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3.ExportIntentsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3.ExportIntentsResponse) com.google.cloud.dialogflow.cx.v3.ExportIntentsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3.IntentProto .internal_static_google_cloud_dialogflow_cx_v3_ExportIntentsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3.IntentProto .internal_static_google_cloud_dialogflow_cx_v3_ExportIntentsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse.class, com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (intentsContentBuilder_ != null) { intentsContentBuilder_.clear(); } intentsCase_ = 0; intents_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.cx.v3.IntentProto .internal_static_google_cloud_dialogflow_cx_v3_ExportIntentsResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse build() { com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse buildPartial() { com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse result = new com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs( com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse result) { result.intentsCase_ = intentsCase_; result.intents_ = this.intents_; if (intentsCase_ == 2 && intentsContentBuilder_ != null) { result.intents_ = intentsContentBuilder_.build(); } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse) { return mergeFrom((com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse other) { if (other == com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse.getDefaultInstance()) return this; switch (other.getIntentsCase()) { case INTENTS_URI: { intentsCase_ = 1; intents_ = other.intents_; onChanged(); break; } case INTENTS_CONTENT: { mergeIntentsContent(other.getIntentsContent()); break; } case INTENTS_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); intentsCase_ = 1; intents_ = s; break; } // case 10 case 18: { input.readMessage(getIntentsContentFieldBuilder().getBuilder(), extensionRegistry); intentsCase_ = 2; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int intentsCase_ = 0; private java.lang.Object intents_; public IntentsCase getIntentsCase() { return IntentsCase.forNumber(intentsCase_); } public Builder clearIntents() { intentsCase_ = 0; intents_ = null; onChanged(); return this; } private int bitField0_; /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @return Whether the intentsUri field is set. */ @java.lang.Override public boolean hasIntentsUri() { return intentsCase_ == 1; } /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @return The intentsUri. */ @java.lang.Override public java.lang.String getIntentsUri() { java.lang.Object ref = ""; if (intentsCase_ == 1) { ref = intents_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (intentsCase_ == 1) { intents_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @return The bytes for intentsUri. */ @java.lang.Override public com.google.protobuf.ByteString getIntentsUriBytes() { java.lang.Object ref = ""; if (intentsCase_ == 1) { ref = intents_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (intentsCase_ == 1) { intents_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @param value The intentsUri to set. * @return This builder for chaining. */ public Builder setIntentsUri(java.lang.String value) { if (value == null) { throw new NullPointerException(); } intentsCase_ = 1; intents_ = value; onChanged(); return this; } /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @return This builder for chaining. */ public Builder clearIntentsUri() { if (intentsCase_ == 1) { intentsCase_ = 0; intents_ = null; onChanged(); } return this; } /** * * * <pre> * The URI to a file containing the exported intents. This field is * populated only if `intents_uri` is specified in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>string intents_uri = 1;</code> * * @param value The bytes for intentsUri to set. * @return This builder for chaining. */ public Builder setIntentsUriBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); intentsCase_ = 1; intents_ = value; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.cx.v3.InlineDestination, com.google.cloud.dialogflow.cx.v3.InlineDestination.Builder, com.google.cloud.dialogflow.cx.v3.InlineDestinationOrBuilder> intentsContentBuilder_; /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> * * @return Whether the intentsContent field is set. */ @java.lang.Override public boolean hasIntentsContent() { return intentsCase_ == 2; } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> * * @return The intentsContent. */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3.InlineDestination getIntentsContent() { if (intentsContentBuilder_ == null) { if (intentsCase_ == 2) { return (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_; } return com.google.cloud.dialogflow.cx.v3.InlineDestination.getDefaultInstance(); } else { if (intentsCase_ == 2) { return intentsContentBuilder_.getMessage(); } return com.google.cloud.dialogflow.cx.v3.InlineDestination.getDefaultInstance(); } } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ public Builder setIntentsContent(com.google.cloud.dialogflow.cx.v3.InlineDestination value) { if (intentsContentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } intents_ = value; onChanged(); } else { intentsContentBuilder_.setMessage(value); } intentsCase_ = 2; return this; } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ public Builder setIntentsContent( com.google.cloud.dialogflow.cx.v3.InlineDestination.Builder builderForValue) { if (intentsContentBuilder_ == null) { intents_ = builderForValue.build(); onChanged(); } else { intentsContentBuilder_.setMessage(builderForValue.build()); } intentsCase_ = 2; return this; } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ public Builder mergeIntentsContent(com.google.cloud.dialogflow.cx.v3.InlineDestination value) { if (intentsContentBuilder_ == null) { if (intentsCase_ == 2 && intents_ != com.google.cloud.dialogflow.cx.v3.InlineDestination.getDefaultInstance()) { intents_ = com.google.cloud.dialogflow.cx.v3.InlineDestination.newBuilder( (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_) .mergeFrom(value) .buildPartial(); } else { intents_ = value; } onChanged(); } else { if (intentsCase_ == 2) { intentsContentBuilder_.mergeFrom(value); } else { intentsContentBuilder_.setMessage(value); } } intentsCase_ = 2; return this; } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ public Builder clearIntentsContent() { if (intentsContentBuilder_ == null) { if (intentsCase_ == 2) { intentsCase_ = 0; intents_ = null; onChanged(); } } else { if (intentsCase_ == 2) { intentsCase_ = 0; intents_ = null; } intentsContentBuilder_.clear(); } return this; } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ public com.google.cloud.dialogflow.cx.v3.InlineDestination.Builder getIntentsContentBuilder() { return getIntentsContentFieldBuilder().getBuilder(); } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3.InlineDestinationOrBuilder getIntentsContentOrBuilder() { if ((intentsCase_ == 2) && (intentsContentBuilder_ != null)) { return intentsContentBuilder_.getMessageOrBuilder(); } else { if (intentsCase_ == 2) { return (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_; } return com.google.cloud.dialogflow.cx.v3.InlineDestination.getDefaultInstance(); } } /** * * * <pre> * Uncompressed byte content for intents. This field is populated only if * `intents_content_inline` is set to true in * [ExportIntentsRequest][google.cloud.dialogflow.cx.v3.ExportIntentsRequest]. * </pre> * * <code>.google.cloud.dialogflow.cx.v3.InlineDestination intents_content = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.cx.v3.InlineDestination, com.google.cloud.dialogflow.cx.v3.InlineDestination.Builder, com.google.cloud.dialogflow.cx.v3.InlineDestinationOrBuilder> getIntentsContentFieldBuilder() { if (intentsContentBuilder_ == null) { if (!(intentsCase_ == 2)) { intents_ = com.google.cloud.dialogflow.cx.v3.InlineDestination.getDefaultInstance(); } intentsContentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.cx.v3.InlineDestination, com.google.cloud.dialogflow.cx.v3.InlineDestination.Builder, com.google.cloud.dialogflow.cx.v3.InlineDestinationOrBuilder>( (com.google.cloud.dialogflow.cx.v3.InlineDestination) intents_, getParentForChildren(), isClean()); intents_ = null; } intentsCase_ = 2; onChanged(); return intentsContentBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.cx.v3.ExportIntentsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3.ExportIntentsResponse) private static final com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse(); } public static com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExportIntentsResponse> PARSER = new com.google.protobuf.AbstractParser<ExportIntentsResponse>() { @java.lang.Override public ExportIntentsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ExportIntentsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExportIntentsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.ExportIntentsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,568
java-shopping-merchant-accounts/grpc-google-shopping-merchant-accounts-v1beta/src/main/java/com/google/shopping/merchant/accounts/v1beta/CheckoutSettingsServiceGrpc.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.shopping.merchant.accounts.v1beta; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * * * <pre> * Service for supporting [checkout * settings](https://support.google.com/merchants/answer/13945960). * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/shopping/merchant/accounts/v1beta/checkoutsettings.proto") @io.grpc.stub.annotations.GrpcGenerated public final class CheckoutSettingsServiceGrpc { private CheckoutSettingsServiceGrpc() {} public static final java.lang.String SERVICE_NAME = "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getGetCheckoutSettingsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetCheckoutSettings", requestType = com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest.class, responseType = com.google.shopping.merchant.accounts.v1beta.CheckoutSettings.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getGetCheckoutSettingsMethod() { io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getGetCheckoutSettingsMethod; if ((getGetCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getGetCheckoutSettingsMethod) == null) { synchronized (CheckoutSettingsServiceGrpc.class) { if ((getGetCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getGetCheckoutSettingsMethod) == null) { CheckoutSettingsServiceGrpc.getGetCheckoutSettingsMethod = getGetCheckoutSettingsMethod = io.grpc.MethodDescriptor .<com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "GetCheckoutSettings")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.shopping.merchant.accounts.v1beta .GetCheckoutSettingsRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.shopping.merchant.accounts.v1beta.CheckoutSettings .getDefaultInstance())) .setSchemaDescriptor( new CheckoutSettingsServiceMethodDescriptorSupplier( "GetCheckoutSettings")) .build(); } } } return getGetCheckoutSettingsMethod; } private static volatile io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getCreateCheckoutSettingsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateCheckoutSettings", requestType = com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest.class, responseType = com.google.shopping.merchant.accounts.v1beta.CheckoutSettings.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getCreateCheckoutSettingsMethod() { io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getCreateCheckoutSettingsMethod; if ((getCreateCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getCreateCheckoutSettingsMethod) == null) { synchronized (CheckoutSettingsServiceGrpc.class) { if ((getCreateCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getCreateCheckoutSettingsMethod) == null) { CheckoutSettingsServiceGrpc.getCreateCheckoutSettingsMethod = getCreateCheckoutSettingsMethod = io.grpc.MethodDescriptor .<com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "CreateCheckoutSettings")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.shopping.merchant.accounts.v1beta .CreateCheckoutSettingsRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.shopping.merchant.accounts.v1beta.CheckoutSettings .getDefaultInstance())) .setSchemaDescriptor( new CheckoutSettingsServiceMethodDescriptorSupplier( "CreateCheckoutSettings")) .build(); } } } return getCreateCheckoutSettingsMethod; } private static volatile io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getUpdateCheckoutSettingsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UpdateCheckoutSettings", requestType = com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest.class, responseType = com.google.shopping.merchant.accounts.v1beta.CheckoutSettings.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getUpdateCheckoutSettingsMethod() { io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getUpdateCheckoutSettingsMethod; if ((getUpdateCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getUpdateCheckoutSettingsMethod) == null) { synchronized (CheckoutSettingsServiceGrpc.class) { if ((getUpdateCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getUpdateCheckoutSettingsMethod) == null) { CheckoutSettingsServiceGrpc.getUpdateCheckoutSettingsMethod = getUpdateCheckoutSettingsMethod = io.grpc.MethodDescriptor .<com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "UpdateCheckoutSettings")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.shopping.merchant.accounts.v1beta .UpdateCheckoutSettingsRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.shopping.merchant.accounts.v1beta.CheckoutSettings .getDefaultInstance())) .setSchemaDescriptor( new CheckoutSettingsServiceMethodDescriptorSupplier( "UpdateCheckoutSettings")) .build(); } } } return getUpdateCheckoutSettingsMethod; } private static volatile io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest, com.google.protobuf.Empty> getDeleteCheckoutSettingsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "DeleteCheckoutSettings", requestType = com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest.class, responseType = com.google.protobuf.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest, com.google.protobuf.Empty> getDeleteCheckoutSettingsMethod() { io.grpc.MethodDescriptor< com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest, com.google.protobuf.Empty> getDeleteCheckoutSettingsMethod; if ((getDeleteCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getDeleteCheckoutSettingsMethod) == null) { synchronized (CheckoutSettingsServiceGrpc.class) { if ((getDeleteCheckoutSettingsMethod = CheckoutSettingsServiceGrpc.getDeleteCheckoutSettingsMethod) == null) { CheckoutSettingsServiceGrpc.getDeleteCheckoutSettingsMethod = getDeleteCheckoutSettingsMethod = io.grpc.MethodDescriptor .<com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest, com.google.protobuf.Empty> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "DeleteCheckoutSettings")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.shopping.merchant.accounts.v1beta .DeleteCheckoutSettingsRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.protobuf.Empty.getDefaultInstance())) .setSchemaDescriptor( new CheckoutSettingsServiceMethodDescriptorSupplier( "DeleteCheckoutSettings")) .build(); } } } return getDeleteCheckoutSettingsMethod; } /** Creates a new async stub that supports all call types for the service */ public static CheckoutSettingsServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceStub>() { @java.lang.Override public CheckoutSettingsServiceStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceStub(channel, callOptions); } }; return CheckoutSettingsServiceStub.newStub(factory, channel); } /** Creates a new blocking-style stub that supports all types of calls on the service */ public static CheckoutSettingsServiceBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceBlockingV2Stub> factory = new io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceBlockingV2Stub>() { @java.lang.Override public CheckoutSettingsServiceBlockingV2Stub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceBlockingV2Stub(channel, callOptions); } }; return CheckoutSettingsServiceBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static CheckoutSettingsServiceBlockingStub newBlockingStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceBlockingStub>() { @java.lang.Override public CheckoutSettingsServiceBlockingStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceBlockingStub(channel, callOptions); } }; return CheckoutSettingsServiceBlockingStub.newStub(factory, channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static CheckoutSettingsServiceFutureStub newFutureStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<CheckoutSettingsServiceFutureStub>() { @java.lang.Override public CheckoutSettingsServiceFutureStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceFutureStub(channel, callOptions); } }; return CheckoutSettingsServiceFutureStub.newStub(factory, channel); } /** * * * <pre> * Service for supporting [checkout * settings](https://support.google.com/merchants/answer/13945960). * </pre> */ public interface AsyncService { /** * * * <pre> * Gets `CheckoutSettings` for the given merchant. This includes * information about review state, enrollment state and URL settings. * </pre> */ default void getCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getGetCheckoutSettingsMethod(), responseObserver); } /** * * * <pre> * Creates `CheckoutSettings` for the given merchant. * </pre> */ default void createCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getCreateCheckoutSettingsMethod(), responseObserver); } /** * * * <pre> * Updates `CheckoutSettings` for the given merchant. * </pre> */ default void updateCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getUpdateCheckoutSettingsMethod(), responseObserver); } /** * * * <pre> * Deletes `CheckoutSettings` and unenrolls merchant from * `Checkout` program. * </pre> */ default void deleteCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getDeleteCheckoutSettingsMethod(), responseObserver); } } /** * Base class for the server implementation of the service CheckoutSettingsService. * * <pre> * Service for supporting [checkout * settings](https://support.google.com/merchants/answer/13945960). * </pre> */ public abstract static class CheckoutSettingsServiceImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return CheckoutSettingsServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service CheckoutSettingsService. * * <pre> * Service for supporting [checkout * settings](https://support.google.com/merchants/answer/13945960). * </pre> */ public static final class CheckoutSettingsServiceStub extends io.grpc.stub.AbstractAsyncStub<CheckoutSettingsServiceStub> { private CheckoutSettingsServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CheckoutSettingsServiceStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceStub(channel, callOptions); } /** * * * <pre> * Gets `CheckoutSettings` for the given merchant. This includes * information about review state, enrollment state and URL settings. * </pre> */ public void getCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetCheckoutSettingsMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Creates `CheckoutSettings` for the given merchant. * </pre> */ public void createCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateCheckoutSettingsMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Updates `CheckoutSettings` for the given merchant. * </pre> */ public void updateCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getUpdateCheckoutSettingsMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Deletes `CheckoutSettings` and unenrolls merchant from * `Checkout` program. * </pre> */ public void deleteCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getDeleteCheckoutSettingsMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service CheckoutSettingsService. * * <pre> * Service for supporting [checkout * settings](https://support.google.com/merchants/answer/13945960). * </pre> */ public static final class CheckoutSettingsServiceBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub<CheckoutSettingsServiceBlockingV2Stub> { private CheckoutSettingsServiceBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CheckoutSettingsServiceBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceBlockingV2Stub(channel, callOptions); } /** * * * <pre> * Gets `CheckoutSettings` for the given merchant. This includes * information about review state, enrollment state and URL settings. * </pre> */ public com.google.shopping.merchant.accounts.v1beta.CheckoutSettings getCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetCheckoutSettingsMethod(), getCallOptions(), request); } /** * * * <pre> * Creates `CheckoutSettings` for the given merchant. * </pre> */ public com.google.shopping.merchant.accounts.v1beta.CheckoutSettings createCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateCheckoutSettingsMethod(), getCallOptions(), request); } /** * * * <pre> * Updates `CheckoutSettings` for the given merchant. * </pre> */ public com.google.shopping.merchant.accounts.v1beta.CheckoutSettings updateCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateCheckoutSettingsMethod(), getCallOptions(), request); } /** * * * <pre> * Deletes `CheckoutSettings` and unenrolls merchant from * `Checkout` program. * </pre> */ public com.google.protobuf.Empty deleteCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDeleteCheckoutSettingsMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service CheckoutSettingsService. * * <pre> * Service for supporting [checkout * settings](https://support.google.com/merchants/answer/13945960). * </pre> */ public static final class CheckoutSettingsServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<CheckoutSettingsServiceBlockingStub> { private CheckoutSettingsServiceBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CheckoutSettingsServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceBlockingStub(channel, callOptions); } /** * * * <pre> * Gets `CheckoutSettings` for the given merchant. This includes * information about review state, enrollment state and URL settings. * </pre> */ public com.google.shopping.merchant.accounts.v1beta.CheckoutSettings getCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetCheckoutSettingsMethod(), getCallOptions(), request); } /** * * * <pre> * Creates `CheckoutSettings` for the given merchant. * </pre> */ public com.google.shopping.merchant.accounts.v1beta.CheckoutSettings createCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateCheckoutSettingsMethod(), getCallOptions(), request); } /** * * * <pre> * Updates `CheckoutSettings` for the given merchant. * </pre> */ public com.google.shopping.merchant.accounts.v1beta.CheckoutSettings updateCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateCheckoutSettingsMethod(), getCallOptions(), request); } /** * * * <pre> * Deletes `CheckoutSettings` and unenrolls merchant from * `Checkout` program. * </pre> */ public com.google.protobuf.Empty deleteCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDeleteCheckoutSettingsMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service * CheckoutSettingsService. * * <pre> * Service for supporting [checkout * settings](https://support.google.com/merchants/answer/13945960). * </pre> */ public static final class CheckoutSettingsServiceFutureStub extends io.grpc.stub.AbstractFutureStub<CheckoutSettingsServiceFutureStub> { private CheckoutSettingsServiceFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected CheckoutSettingsServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new CheckoutSettingsServiceFutureStub(channel, callOptions); } /** * * * <pre> * Gets `CheckoutSettings` for the given merchant. This includes * information about review state, enrollment state and URL settings. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> getCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetCheckoutSettingsMethod(), getCallOptions()), request); } /** * * * <pre> * Creates `CheckoutSettings` for the given merchant. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> createCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateCheckoutSettingsMethod(), getCallOptions()), request); } /** * * * <pre> * Updates `CheckoutSettings` for the given merchant. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.shopping.merchant.accounts.v1beta.CheckoutSettings> updateCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getUpdateCheckoutSettingsMethod(), getCallOptions()), request); } /** * * * <pre> * Deletes `CheckoutSettings` and unenrolls merchant from * `Checkout` program. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty> deleteCheckoutSettings( com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getDeleteCheckoutSettingsMethod(), getCallOptions()), request); } } private static final int METHODID_GET_CHECKOUT_SETTINGS = 0; private static final int METHODID_CREATE_CHECKOUT_SETTINGS = 1; private static final int METHODID_UPDATE_CHECKOUT_SETTINGS = 2; private static final int METHODID_DELETE_CHECKOUT_SETTINGS = 3; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_GET_CHECKOUT_SETTINGS: serviceImpl.getCheckoutSettings( (com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest) request, (io.grpc.stub.StreamObserver< com.google.shopping.merchant.accounts.v1beta.CheckoutSettings>) responseObserver); break; case METHODID_CREATE_CHECKOUT_SETTINGS: serviceImpl.createCheckoutSettings( (com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest) request, (io.grpc.stub.StreamObserver< com.google.shopping.merchant.accounts.v1beta.CheckoutSettings>) responseObserver); break; case METHODID_UPDATE_CHECKOUT_SETTINGS: serviceImpl.updateCheckoutSettings( (com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest) request, (io.grpc.stub.StreamObserver< com.google.shopping.merchant.accounts.v1beta.CheckoutSettings>) responseObserver); break; case METHODID_DELETE_CHECKOUT_SETTINGS: serviceImpl.deleteCheckoutSettings( (com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest) request, (io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getGetCheckoutSettingsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.shopping.merchant.accounts.v1beta.GetCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings>( service, METHODID_GET_CHECKOUT_SETTINGS))) .addMethod( getCreateCheckoutSettingsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.shopping.merchant.accounts.v1beta.CreateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings>( service, METHODID_CREATE_CHECKOUT_SETTINGS))) .addMethod( getUpdateCheckoutSettingsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.shopping.merchant.accounts.v1beta.UpdateCheckoutSettingsRequest, com.google.shopping.merchant.accounts.v1beta.CheckoutSettings>( service, METHODID_UPDATE_CHECKOUT_SETTINGS))) .addMethod( getDeleteCheckoutSettingsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.shopping.merchant.accounts.v1beta.DeleteCheckoutSettingsRequest, com.google.protobuf.Empty>(service, METHODID_DELETE_CHECKOUT_SETTINGS))) .build(); } private abstract static class CheckoutSettingsServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { CheckoutSettingsServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.shopping.merchant.accounts.v1beta.CheckoutsettingsProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("CheckoutSettingsService"); } } private static final class CheckoutSettingsServiceFileDescriptorSupplier extends CheckoutSettingsServiceBaseDescriptorSupplier { CheckoutSettingsServiceFileDescriptorSupplier() {} } private static final class CheckoutSettingsServiceMethodDescriptorSupplier extends CheckoutSettingsServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; CheckoutSettingsServiceMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (CheckoutSettingsServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new CheckoutSettingsServiceFileDescriptorSupplier()) .addMethod(getGetCheckoutSettingsMethod()) .addMethod(getCreateCheckoutSettingsMethod()) .addMethod(getUpdateCheckoutSettingsMethod()) .addMethod(getDeleteCheckoutSettingsMethod()) .build(); } } } return result; } }
google/j2objc
36,591
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/GregorianCalendar.java
/* GENERATED SOURCE. DO NOT MODIFY. */ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* * Copyright (C) 1996-2016, International Business Machines * Corporation and others. All Rights Reserved. */ package android.icu.util; import java.util.Date; import java.util.Locale; import android.icu.util.ULocale.Category; /** * <strong>[icu enhancement]</strong> ICU's replacement for {@link java.util.GregorianCalendar}.&nbsp;Methods, fields, and other functionality specific to ICU are labeled '<strong>[icu]</strong>'. * * <p><code>GregorianCalendar</code> is a concrete subclass of * {@link Calendar} * and provides the standard calendar used by most of the world. * * <p>The standard (Gregorian) calendar has 2 eras, BC and AD. * * <p>This implementation handles a single discontinuity, which corresponds by * default to the date the Gregorian calendar was instituted (October 15, 1582 * in some countries, later in others). The cutover date may be changed by the * caller by calling <code>setGregorianChange()</code>. * * <p>Historically, in those countries which adopted the Gregorian calendar first, * October 4, 1582 was thus followed by October 15, 1582. This calendar models * this correctly. Before the Gregorian cutover, <code>GregorianCalendar</code> * implements the Julian calendar. The only difference between the Gregorian * and the Julian calendar is the leap year rule. The Julian calendar specifies * leap years every four years, whereas the Gregorian calendar omits century * years which are not divisible by 400. * * <p><code>GregorianCalendar</code> implements <em>proleptic</em> Gregorian and * Julian calendars. That is, dates are computed by extrapolating the current * rules indefinitely far backward and forward in time. As a result, * <code>GregorianCalendar</code> may be used for all years to generate * meaningful and consistent results. However, dates obtained using * <code>GregorianCalendar</code> are historically accurate only from March 1, 4 * AD onward, when modern Julian calendar rules were adopted. Before this date, * leap year rules were applied irregularly, and before 45 BC the Julian * calendar did not even exist. * * <p>Prior to the institution of the Gregorian calendar, New Year's Day was * March 25. To avoid confusion, this calendar always uses January 1. A manual * adjustment may be made if desired for dates that are prior to the Gregorian * changeover and which fall between January 1 and March 24. * * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to * 53. Week 1 for a year is the earliest seven day period starting on * <code>getFirstDayOfWeek()</code> that contains at least * <code>getMinimalDaysInFirstWeek()</code> days from that year. It thus * depends on the values of <code>getMinimalDaysInFirstWeek()</code>, * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1. * Weeks between week 1 of one year and week 1 of the following year are * numbered sequentially from 2 to 52 or 53 (as needed). * <p>For example, January 1, 1998 was a Thursday. If * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts * on December 29, 1997, and ends on January 4, 1998. If, however, * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998 * starts on January 4, 1998, and ends on January 10, 1998; the first three days * of 1998 then are part of week 53 of 1997. * * <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0 or * 1 to 4 or 5. Week 1 of a month (the days with <code>WEEK_OF_MONTH = * 1</code>) is the earliest set of at least * <code>getMinimalDaysInFirstWeek()</code> contiguous days in that month, * ending on the day before <code>getFirstDayOfWeek()</code>. Unlike * week 1 of a year, week 1 of a month may be shorter than 7 days, need * not start on <code>getFirstDayOfWeek()</code>, and will not include days of * the previous month. Days of a month before week 1 have a * <code>WEEK_OF_MONTH</code> of 0. * * <p>For example, if <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code> * and <code>getMinimalDaysInFirstWeek()</code> is 4, then the first week of * January 1998 is Sunday, January 4 through Saturday, January 10. These days * have a <code>WEEK_OF_MONTH</code> of 1. Thursday, January 1 through * Saturday, January 3 have a <code>WEEK_OF_MONTH</code> of 0. If * <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1 * through January 3 have a <code>WEEK_OF_MONTH</code> of 1. * * <p> * <strong>Example:</strong> * <blockquote> * <pre> * // get the supported ids for GMT-08:00 (Pacific Standard Time) * String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); * // if no ids were returned, something is wrong. get out. * if (ids.length == 0) * System.exit(0); * * // begin output * System.out.println("Current Time"); * * // create a Pacific Standard Time time zone * SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); * * // set up rules for daylight savings time * pdt.setStartRule(Calendar.MARCH, 2, Calendar.SUNDAY, 2 * 60 * 60 * 1000); * pdt.setEndRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); * * // create a GregorianCalendar with the Pacific Daylight time zone * // and the current date and time * Calendar calendar = new GregorianCalendar(pdt); * Date trialTime = new Date(); * calendar.setTime(trialTime); * * // print out a bunch of interesting things * System.out.println("ERA: " + calendar.get(Calendar.ERA)); * System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); * System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); * System.out.println("DATE: " + calendar.get(Calendar.DATE)); * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); * System.out.println("DAY_OF_WEEK_IN_MONTH: " * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); * System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); * System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); * System.out.println("ZONE_OFFSET: " * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); * System.out.println("DST_OFFSET: " * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); * System.out.println("Current Time, with hour reset to 3"); * calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override * calendar.set(Calendar.HOUR, 3); * System.out.println("ERA: " + calendar.get(Calendar.ERA)); * System.out.println("YEAR: " + calendar.get(Calendar.YEAR)); * System.out.println("MONTH: " + calendar.get(Calendar.MONTH)); * System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR)); * System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH)); * System.out.println("DATE: " + calendar.get(Calendar.DATE)); * System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH)); * System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR)); * System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK)); * System.out.println("DAY_OF_WEEK_IN_MONTH: " * + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH)); * System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM)); * System.out.println("HOUR: " + calendar.get(Calendar.HOUR)); * System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY)); * System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE)); * System.out.println("SECOND: " + calendar.get(Calendar.SECOND)); * System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND)); * System.out.println("ZONE_OFFSET: " * + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours * System.out.println("DST_OFFSET: " * + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours</pre> * </blockquote> * <p> * GregorianCalendar usually should be instantiated using * {@link android.icu.util.Calendar#getInstance(ULocale)} passing in a <code>ULocale</code> * with the tag <code>"@calendar=gregorian"</code>.</p> * @see Calendar * @see TimeZone * @author Deborah Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu */ public class GregorianCalendar extends Calendar { // jdk1.4.2 serialver private static final long serialVersionUID = 9199388694351062137L; /* * Implementation Notes * * The Julian day number, as used here, is a modified number which has its * onset at midnight, rather than noon. * * The epoch is the number of days or milliseconds from some defined * starting point. The epoch for java.util.Date is used here; that is, * milliseconds from January 1, 1970 (Gregorian), midnight UTC. Other * epochs which are used are January 1, year 1 (Gregorian), which is day 1 * of the Gregorian calendar, and December 30, year 0 (Gregorian), which is * day 1 of the Julian calendar. * * We implement the proleptic Julian and Gregorian calendars. This means we * implement the modern definition of the calendar even though the * historical usage differs. For example, if the Gregorian change is set * to new Date(Long.MIN_VALUE), we have a pure Gregorian calendar which * labels dates preceding the invention of the Gregorian calendar in 1582 as * if the calendar existed then. * * Likewise, with the Julian calendar, we assume a consistent 4-year leap * rule, even though the historical pattern of leap years is irregular, * being every 3 years from 45 BC through 9 BC, then every 4 years from 8 AD * onwards, with no leap years in-between. Thus date computations and * functions such as isLeapYear() are not intended to be historically * accurate. * * Given that milliseconds are a long, day numbers such as Julian day * numbers, Gregorian or Julian calendar days, or epoch days, are also * longs. Years can fit into an int. */ ////////////////// // Class Variables ////////////////// /** * Value of the <code>ERA</code> field indicating * the period before the common era (before Christ), also known as BCE. * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is * ..., 2 BC, 1 BC, 1 AD, 2 AD,... * @see Calendar#ERA */ public static final int BC = 0; /** * Value of the <code>ERA</code> field indicating * the common era (Anno Domini), also known as CE. * The sequence of years at the transition from <code>BC</code> to <code>AD</code> is * ..., 2 BC, 1 BC, 1 AD, 2 AD,... * @see Calendar#ERA */ public static final int AD = 1; private static final int EPOCH_YEAR = 1970; private static final int[][] MONTH_COUNT = { //len len2 st st2 { 31, 31, 0, 0 }, // Jan { 28, 29, 31, 31 }, // Feb { 31, 31, 59, 60 }, // Mar { 30, 30, 90, 91 }, // Apr { 31, 31, 120, 121 }, // May { 30, 30, 151, 152 }, // Jun { 31, 31, 181, 182 }, // Jul { 31, 31, 212, 213 }, // Aug { 30, 30, 243, 244 }, // Sep { 31, 31, 273, 274 }, // Oct { 30, 30, 304, 305 }, // Nov { 31, 31, 334, 335 } // Dec // len length of month // len2 length of month in a leap year // st days in year before start of month // st2 days in year before month in leap year }; /** * Old year limits were least max 292269054, max 292278994. */ private static final int LIMITS[][] = { // Minimum Greatest Least Maximum // Minimum Maximum { 0, 0, 1, 1 }, // ERA { 1, 1, 5828963, 5838270 }, // YEAR { 0, 0, 11, 11 }, // MONTH { 1, 1, 52, 53 }, // WEEK_OF_YEAR {/* */}, // WEEK_OF_MONTH { 1, 1, 28, 31 }, // DAY_OF_MONTH { 1, 1, 365, 366 }, // DAY_OF_YEAR {/* */}, // DAY_OF_WEEK { -1, -1, 4, 5 }, // DAY_OF_WEEK_IN_MONTH {/* */}, // AM_PM {/* */}, // HOUR {/* */}, // HOUR_OF_DAY {/* */}, // MINUTE {/* */}, // SECOND {/* */}, // MILLISECOND {/* */}, // ZONE_OFFSET {/* */}, // DST_OFFSET { -5838270, -5838270, 5828964, 5838271 }, // YEAR_WOY {/* */}, // DOW_LOCAL { -5838269, -5838269, 5828963, 5838270 }, // EXTENDED_YEAR {/* */}, // JULIAN_DAY {/* */}, // MILLISECONDS_IN_DAY {/* */}, // IS_LEAP_MONTH }; /** */ protected int handleGetLimit(int field, int limitType) { return LIMITS[field][limitType]; } ///////////////////// // Instance Variables ///////////////////// /** * The point at which the Gregorian calendar rules are used, measured in * milliseconds from the standard epoch. Default is October 15, 1582 * (Gregorian) 00:00:00 UTC or -12219292800000L. For this value, October 4, * 1582 (Julian) is followed by October 15, 1582 (Gregorian). This * corresponds to Julian day number 2299161. * @serial */ private long gregorianCutover = -12219292800000L; /** * Julian day number of the Gregorian cutover. */ private transient int cutoverJulianDay = 2299161; /** * The year of the gregorianCutover, with 0 representing * 1 BC, -1 representing 2 BC, etc. */ private transient int gregorianCutoverYear = 1582; /** * Used by handleComputeJulianDay() and handleComputeMonthStart(). */ transient protected boolean isGregorian; /** * Used by handleComputeJulianDay() and handleComputeMonthStart(). */ transient protected boolean invertGregorian; /////////////// // Constructors /////////////// /** * Constructs a default GregorianCalendar using the current time * in the default time zone with the default <code>FORMAT</code> locale. * @see Category#FORMAT */ public GregorianCalendar() { this(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT)); } /** * Constructs a GregorianCalendar based on the current time * in the given time zone with the default <code>FORMAT</code> locale. * @param zone the given time zone. * @see Category#FORMAT */ public GregorianCalendar(TimeZone zone) { this(zone, ULocale.getDefault(Category.FORMAT)); } /** * Constructs a GregorianCalendar based on the current time * in the default time zone with the given locale. * @param aLocale the given locale. */ public GregorianCalendar(Locale aLocale) { this(TimeZone.getDefault(), aLocale); } /** * <strong>[icu]</strong> Constructs a GregorianCalendar based on the current time * in the default time zone with the given locale. * @param locale the given ulocale. */ public GregorianCalendar(ULocale locale) { this(TimeZone.getDefault(), locale); } /** * <strong>[icu]</strong> Constructs a GregorianCalendar based on the current time * in the given time zone with the given locale. * @param zone the given time zone. * @param aLocale the given locale. */ public GregorianCalendar(TimeZone zone, Locale aLocale) { super(zone, aLocale); setTimeInMillis(System.currentTimeMillis()); } /** * Constructs a GregorianCalendar based on the current time * in the given time zone with the given locale. * @param zone the given time zone. * @param locale the given ulocale. */ public GregorianCalendar(TimeZone zone, ULocale locale) { super(zone, locale); setTimeInMillis(System.currentTimeMillis()); } /** * Constructs a GregorianCalendar with the given date set * in the default time zone with the default <code>FORMAT</code> locale. * @param year the value used to set the YEAR time field in the calendar. * @param month the value used to set the MONTH time field in the calendar. * Month value is 0-based. e.g., 0 for January. * @param date the value used to set the DATE time field in the calendar. * @see Category#FORMAT */ public GregorianCalendar(int year, int month, int date) { super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT)); set(ERA, AD); set(YEAR, year); set(MONTH, month); set(DATE, date); } /** * Constructs a GregorianCalendar with the given date * and time set for the default time zone with the default <code>FORMAT</code> locale. * @param year the value used to set the YEAR time field in the calendar. * @param month the value used to set the MONTH time field in the calendar. * Month value is 0-based. e.g., 0 for January. * @param date the value used to set the DATE time field in the calendar. * @param hour the value used to set the HOUR_OF_DAY time field * in the calendar. * @param minute the value used to set the MINUTE time field * in the calendar. * @see Category#FORMAT */ public GregorianCalendar(int year, int month, int date, int hour, int minute) { super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT)); set(ERA, AD); set(YEAR, year); set(MONTH, month); set(DATE, date); set(HOUR_OF_DAY, hour); set(MINUTE, minute); } /** * Constructs a GregorianCalendar with the given date * and time set for the default time zone with the default <code>FORMAT</code> locale. * @param year the value used to set the YEAR time field in the calendar. * @param month the value used to set the MONTH time field in the calendar. * Month value is 0-based. e.g., 0 for January. * @param date the value used to set the DATE time field in the calendar. * @param hour the value used to set the HOUR_OF_DAY time field * in the calendar. * @param minute the value used to set the MINUTE time field * in the calendar. * @param second the value used to set the SECOND time field * in the calendar. * @see Category#FORMAT */ public GregorianCalendar(int year, int month, int date, int hour, int minute, int second) { super(TimeZone.getDefault(), ULocale.getDefault(Category.FORMAT)); set(ERA, AD); set(YEAR, year); set(MONTH, month); set(DATE, date); set(HOUR_OF_DAY, hour); set(MINUTE, minute); set(SECOND, second); } ///////////////// // Public methods ///////////////// /** * Sets the GregorianCalendar change date. This is the point when the switch * from Julian dates to Gregorian dates occurred. Default is October 15, * 1582. Previous to this, dates will be in the Julian calendar. * <p> * To obtain a pure Julian calendar, set the change date to * <code>Date(Long.MAX_VALUE)</code>. To obtain a pure Gregorian calendar, * set the change date to <code>Date(Long.MIN_VALUE)</code>. * * @param date the given Gregorian cutover date. */ public void setGregorianChange(Date date) { gregorianCutover = date.getTime(); // If the cutover has an extreme value, then create a pure // Gregorian or pure Julian calendar by giving the cutover year and // JD extreme values. if (gregorianCutover <= MIN_MILLIS) { gregorianCutoverYear = cutoverJulianDay = Integer.MIN_VALUE; } else if (gregorianCutover >= MAX_MILLIS) { gregorianCutoverYear = cutoverJulianDay = Integer.MAX_VALUE; } else { // Precompute two internal variables which we use to do the actual // cutover computations. These are the Julian day of the cutover // and the cutover year. cutoverJulianDay = (int) floorDivide(gregorianCutover, ONE_DAY); // Convert cutover millis to extended year GregorianCalendar cal = new GregorianCalendar(getTimeZone()); cal.setTime(date); gregorianCutoverYear = cal.get(EXTENDED_YEAR); } } /** * Gets the Gregorian Calendar change date. This is the point when the * switch from Julian dates to Gregorian dates occurred. Default is * October 15, 1582. Previous to this, dates will be in the Julian * calendar. * @return the Gregorian cutover date for this calendar. */ public final Date getGregorianChange() { return new Date(gregorianCutover); } /** * Determines if the given year is a leap year. Returns true if the * given year is a leap year. * @param year the given year. * @return true if the given year is a leap year; false otherwise. */ public boolean isLeapYear(int year) { return year >= gregorianCutoverYear ? ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian (year%4 == 0); // Julian } /** * Returns true if the given Calendar object is equivalent to this * one. Calendar override. * * @param other the Calendar to be compared with this Calendar */ public boolean isEquivalentTo(Calendar other) { return super.isEquivalentTo(other) && gregorianCutover == ((GregorianCalendar)other).gregorianCutover; } /** * Override hashCode. * Generates the hash code for the GregorianCalendar object */ public int hashCode() { return super.hashCode() ^ (int)gregorianCutover; } /** * Roll a field by a signed amount. */ public void roll(int field, int amount) { switch (field) { case WEEK_OF_YEAR: { // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the // week. Also, rolling the week of the year can have seemingly // strange effects simply because the year of the week of year // may be different from the calendar year. For example, the // date Dec 28, 1997 is the first day of week 1 of 1998 (if // weeks start on Sunday and the minimal days in first week is // <= 3). int woy = get(WEEK_OF_YEAR); // Get the ISO year, which matches the week of year. This // may be one year before or after the calendar year. int isoYear = get(YEAR_WOY); int isoDoy = internalGet(DAY_OF_YEAR); if (internalGet(MONTH) == Calendar.JANUARY) { if (woy >= 52) { isoDoy += handleGetYearLength(isoYear); } } else { if (woy == 1) { isoDoy -= handleGetYearLength(isoYear - 1); } } woy += amount; // Do fast checks to avoid unnecessary computation: if (woy < 1 || woy > 52) { // Determine the last week of the ISO year. // We do this using the standard formula we use // everywhere in this file. If we can see that the // days at the end of the year are going to fall into // week 1 of the next year, we drop the last week by // subtracting 7 from the last day of the year. int lastDoy = handleGetYearLength(isoYear); int lastRelDow = (lastDoy - isoDoy + internalGet(DAY_OF_WEEK) - getFirstDayOfWeek()) % 7; if (lastRelDow < 0) lastRelDow += 7; if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7; int lastWoy = weekNumber(lastDoy, lastRelDow + 1); woy = ((woy + lastWoy - 1) % lastWoy) + 1; } set(WEEK_OF_YEAR, woy); set(YEAR, isoYear); // Why not YEAR_WOY? - Alan 11/6/00 return; } default: super.roll(field, amount); return; } } /** * Return the minimum value that this field could have, given the current date. * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). */ public int getActualMinimum(int field) { return getMinimum(field); } /** * Return the maximum value that this field could have, given the current date. * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, * for some years the actual maximum for MONTH is 12, and for others 13. */ public int getActualMaximum(int field) { /* It is a known limitation that the code here (and in getActualMinimum) * won't behave properly at the extreme limits of GregorianCalendar's * representable range (except for the code that handles the YEAR * field). That's because the ends of the representable range are at * odd spots in the year. For calendars with the default Gregorian * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT * zones. As a result, if the calendar is set to Aug 1 292278994 AD, * the actual maximum of DAY_OF_MONTH is 17, not 30. If the date is Mar * 31 in that year, the actual maximum month might be Jul, whereas is * the date is Mar 15, the actual maximum might be Aug -- depending on * the precise semantics that are desired. Similar considerations * affect all fields. Nonetheless, this effect is sufficiently arcane * that we permit it, rather than complicating the code to handle such * intricacies. - liu 8/20/98 * UPDATE: No longer true, since we have pulled in the limit values on * the year. - Liu 11/6/00 */ switch (field) { case YEAR: /* The year computation is no different, in principle, from the * others, however, the range of possible maxima is large. In * addition, the way we know we've exceeded the range is different. * For these reasons, we use the special case code below to handle * this field. * * The actual maxima for YEAR depend on the type of calendar: * * Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD * Julian = Dec 2, 292269055 BC - Jan 3, 292272993 AD * Hybrid = Dec 2, 292269055 BC - Aug 17, 292278994 AD * * We know we've exceeded the maximum when either the month, date, * time, or era changes in response to setting the year. We don't * check for month, date, and time here because the year and era are * sufficient to detect an invalid year setting. NOTE: If code is * added to check the month and date in the future for some reason, * Feb 29 must be allowed to shift to Mar 1 when setting the year. */ { Calendar cal = (Calendar) clone(); cal.setLenient(true); int era = cal.get(ERA); Date d = cal.getTime(); /* Perform a binary search, with the invariant that lowGood is a * valid year, and highBad is an out of range year. */ int lowGood = LIMITS[YEAR][1]; int highBad = LIMITS[YEAR][2]+1; while ((lowGood + 1) < highBad) { int y = (lowGood + highBad) / 2; cal.set(YEAR, y); if (cal.get(YEAR) == y && cal.get(ERA) == era) { lowGood = y; } else { highBad = y; cal.setTime(d); // Restore original fields } } return lowGood; } default: return super.getActualMaximum(field); } } ////////////////////// // Proposed public API ////////////////////// /** * Return true if the current time for this Calendar is in Daylignt * Savings Time. */ boolean inDaylightTime() { if (!getTimeZone().useDaylightTime()) return false; complete(); // Force update of DST_OFFSET field return internalGet(DST_OFFSET) != 0; } ///////////////////// // Calendar framework ///////////////////// /** */ protected int handleGetMonthLength(int extendedYear, int month) { // If the month is out of range, adjust it into range, and // modify the extended year value accordingly. if (month < 0 || month > 11) { int[] rem = new int[1]; extendedYear += floorDivide(month, 12, rem); month = rem[0]; } return MONTH_COUNT[month][isLeapYear(extendedYear)?1:0]; } /** */ protected int handleGetYearLength(int eyear) { return isLeapYear(eyear) ? 366 : 365; } ///////////////////////////// // Time => Fields computation ///////////////////////////// /** * Override Calendar to compute several fields specific to the hybrid * Gregorian-Julian calendar system. These are: * * <ul><li>ERA * <li>YEAR * <li>MONTH * <li>DAY_OF_MONTH * <li>DAY_OF_YEAR * <li>EXTENDED_YEAR</ul> */ protected void handleComputeFields(int julianDay) { int eyear, month, dayOfMonth, dayOfYear; if (julianDay >= cutoverJulianDay) { month = getGregorianMonth(); dayOfMonth = getGregorianDayOfMonth(); dayOfYear = getGregorianDayOfYear(); eyear = getGregorianYear(); } else { // The Julian epoch day (not the same as Julian Day) // is zero on Saturday December 30, 0 (Gregorian). long julianEpochDay = julianDay - (JAN_1_1_JULIAN_DAY - 2); eyear = (int) floorDivide(4*julianEpochDay + 1464, 1461); // Compute the Julian calendar day number for January 1, eyear long january1 = 365L*(eyear-1L) + floorDivide(eyear-1L, 4L); dayOfYear = (int)(julianEpochDay - january1); // 0-based // Julian leap years occurred historically every 4 years starting // with 8 AD. Before 8 AD the spacing is irregular; every 3 years // from 45 BC to 9 BC, and then none until 8 AD. However, we don't // implement this historical detail; instead, we implement the // computatinally cleaner proleptic calendar, which assumes // consistent 4-year cycles throughout time. boolean isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0) // Common Julian/Gregorian calculation int correction = 0; int march1 = isLeap ? 60 : 59; // zero-based DOY for March 1 if (dayOfYear >= march1) { correction = isLeap ? 1 : 2; } month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month dayOfMonth = dayOfYear - MONTH_COUNT[month][isLeap?3:2] + 1; // one-based DOM ++dayOfYear; } internalSet(MONTH, month); internalSet(DAY_OF_MONTH, dayOfMonth); internalSet(DAY_OF_YEAR, dayOfYear); internalSet(EXTENDED_YEAR, eyear); int era = AD; if (eyear < 1) { era = BC; eyear = 1 - eyear; } internalSet(ERA, era); internalSet(YEAR, eyear); } ///////////////////////////// // Fields => Time computation ///////////////////////////// /** */ protected int handleGetExtendedYear() { int year; if (newerField(EXTENDED_YEAR, YEAR) == EXTENDED_YEAR) { year = internalGet(EXTENDED_YEAR, EPOCH_YEAR); } else { // The year defaults to the epoch start, the era to AD int era = internalGet(ERA, AD); if (era == BC) { year = 1 - internalGet(YEAR, 1); // Convert to extended year } else { year = internalGet(YEAR, EPOCH_YEAR); } } return year; } /** */ protected int handleComputeJulianDay(int bestField) { invertGregorian = false; int jd = super.handleComputeJulianDay(bestField); // The following check handles portions of the cutover year BEFORE the // cutover itself happens. if (isGregorian != (jd >= cutoverJulianDay)) { invertGregorian = true; jd = super.handleComputeJulianDay(bestField); } return jd; } /** * Return JD of start of given month/year */ protected int handleComputeMonthStart(int eyear, int month, boolean useMonth) { // If the month is out of range, adjust it into range, and // modify the extended year value accordingly. if (month < 0 || month > 11) { int[] rem = new int[1]; eyear += floorDivide(month, 12, rem); month = rem[0]; } boolean isLeap = eyear%4 == 0; int y = eyear - 1; int julianDay = 365*y + floorDivide(y, 4) + (JAN_1_1_JULIAN_DAY - 3); isGregorian = (eyear >= gregorianCutoverYear); if (invertGregorian) { isGregorian = !isGregorian; } if (isGregorian) { isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0)); // Add 2 because Gregorian calendar starts 2 days after // Julian calendar julianDay += floorDivide(y, 400) - floorDivide(y, 100) + 2; } // At this point julianDay indicates the day BEFORE the first // day of January 1, <eyear> of either the Julian or Gregorian // calendar. if (month != 0) { julianDay += MONTH_COUNT[month][isLeap?3:2]; } return julianDay; } /** * {@inheritDoc} */ public String getType() { return "gregorian"; } /* private static CalendarFactory factory; public static CalendarFactory factory() { if (factory == null) { factory = new CalendarFactory() { public Calendar create(TimeZone tz, ULocale loc) { return new GregorianCalendar(tz, loc); } public String factoryName() { return "Gregorian"; } }; } return factory; } */ }
googleapis/google-cloud-java
36,347
java-datalabeling/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/ListDataItemsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datalabeling/v1beta1/data_labeling_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datalabeling.v1beta1; /** * * * <pre> * Results of listing data items in a dataset. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListDataItemsResponse} */ public final class ListDataItemsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.ListDataItemsResponse) ListDataItemsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDataItemsResponse.newBuilder() to construct. private ListDataItemsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDataItemsResponse() { dataItems_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDataItemsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDataItemsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDataItemsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse.class, com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse.Builder.class); } public static final int DATA_ITEMS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.datalabeling.v1beta1.DataItem> dataItems_; /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.datalabeling.v1beta1.DataItem> getDataItemsList() { return dataItems_; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.datalabeling.v1beta1.DataItemOrBuilder> getDataItemsOrBuilderList() { return dataItems_; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ @java.lang.Override public int getDataItemsCount() { return dataItems_.size(); } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.DataItem getDataItems(int index) { return dataItems_.get(index); } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ @java.lang.Override public com.google.cloud.datalabeling.v1beta1.DataItemOrBuilder getDataItemsOrBuilder(int index) { return dataItems_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < dataItems_.size(); i++) { output.writeMessage(1, dataItems_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < dataItems_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dataItems_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse)) { return super.equals(obj); } com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse other = (com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse) obj; if (!getDataItemsList().equals(other.getDataItemsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getDataItemsCount() > 0) { hash = (37 * hash) + DATA_ITEMS_FIELD_NUMBER; hash = (53 * hash) + getDataItemsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Results of listing data items in a dataset. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListDataItemsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.ListDataItemsResponse) com.google.cloud.datalabeling.v1beta1.ListDataItemsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDataItemsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDataItemsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse.class, com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse.Builder.class); } // Construct using com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dataItemsBuilder_ == null) { dataItems_ = java.util.Collections.emptyList(); } else { dataItems_ = null; dataItemsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDataItemsResponse_descriptor; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse getDefaultInstanceForType() { return com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse build() { com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse buildPartial() { com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse result = new com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse result) { if (dataItemsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dataItems_ = java.util.Collections.unmodifiableList(dataItems_); bitField0_ = (bitField0_ & ~0x00000001); } result.dataItems_ = dataItems_; } else { result.dataItems_ = dataItemsBuilder_.build(); } } private void buildPartial0(com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse) { return mergeFrom((com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse other) { if (other == com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse.getDefaultInstance()) return this; if (dataItemsBuilder_ == null) { if (!other.dataItems_.isEmpty()) { if (dataItems_.isEmpty()) { dataItems_ = other.dataItems_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDataItemsIsMutable(); dataItems_.addAll(other.dataItems_); } onChanged(); } } else { if (!other.dataItems_.isEmpty()) { if (dataItemsBuilder_.isEmpty()) { dataItemsBuilder_.dispose(); dataItemsBuilder_ = null; dataItems_ = other.dataItems_; bitField0_ = (bitField0_ & ~0x00000001); dataItemsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDataItemsFieldBuilder() : null; } else { dataItemsBuilder_.addAllMessages(other.dataItems_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.datalabeling.v1beta1.DataItem m = input.readMessage( com.google.cloud.datalabeling.v1beta1.DataItem.parser(), extensionRegistry); if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.add(m); } else { dataItemsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.datalabeling.v1beta1.DataItem> dataItems_ = java.util.Collections.emptyList(); private void ensureDataItemsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dataItems_ = new java.util.ArrayList<com.google.cloud.datalabeling.v1beta1.DataItem>(dataItems_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.DataItem, com.google.cloud.datalabeling.v1beta1.DataItem.Builder, com.google.cloud.datalabeling.v1beta1.DataItemOrBuilder> dataItemsBuilder_; /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public java.util.List<com.google.cloud.datalabeling.v1beta1.DataItem> getDataItemsList() { if (dataItemsBuilder_ == null) { return java.util.Collections.unmodifiableList(dataItems_); } else { return dataItemsBuilder_.getMessageList(); } } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public int getDataItemsCount() { if (dataItemsBuilder_ == null) { return dataItems_.size(); } else { return dataItemsBuilder_.getCount(); } } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.DataItem getDataItems(int index) { if (dataItemsBuilder_ == null) { return dataItems_.get(index); } else { return dataItemsBuilder_.getMessage(index); } } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder setDataItems(int index, com.google.cloud.datalabeling.v1beta1.DataItem value) { if (dataItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataItemsIsMutable(); dataItems_.set(index, value); onChanged(); } else { dataItemsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder setDataItems( int index, com.google.cloud.datalabeling.v1beta1.DataItem.Builder builderForValue) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.set(index, builderForValue.build()); onChanged(); } else { dataItemsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder addDataItems(com.google.cloud.datalabeling.v1beta1.DataItem value) { if (dataItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataItemsIsMutable(); dataItems_.add(value); onChanged(); } else { dataItemsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder addDataItems(int index, com.google.cloud.datalabeling.v1beta1.DataItem value) { if (dataItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataItemsIsMutable(); dataItems_.add(index, value); onChanged(); } else { dataItemsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder addDataItems( com.google.cloud.datalabeling.v1beta1.DataItem.Builder builderForValue) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.add(builderForValue.build()); onChanged(); } else { dataItemsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder addDataItems( int index, com.google.cloud.datalabeling.v1beta1.DataItem.Builder builderForValue) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.add(index, builderForValue.build()); onChanged(); } else { dataItemsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder addAllDataItems( java.lang.Iterable<? extends com.google.cloud.datalabeling.v1beta1.DataItem> values) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dataItems_); onChanged(); } else { dataItemsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder clearDataItems() { if (dataItemsBuilder_ == null) { dataItems_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dataItemsBuilder_.clear(); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public Builder removeDataItems(int index) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.remove(index); onChanged(); } else { dataItemsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.DataItem.Builder getDataItemsBuilder(int index) { return getDataItemsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.DataItemOrBuilder getDataItemsOrBuilder( int index) { if (dataItemsBuilder_ == null) { return dataItems_.get(index); } else { return dataItemsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public java.util.List<? extends com.google.cloud.datalabeling.v1beta1.DataItemOrBuilder> getDataItemsOrBuilderList() { if (dataItemsBuilder_ != null) { return dataItemsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dataItems_); } } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.DataItem.Builder addDataItemsBuilder() { return getDataItemsFieldBuilder() .addBuilder(com.google.cloud.datalabeling.v1beta1.DataItem.getDefaultInstance()); } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public com.google.cloud.datalabeling.v1beta1.DataItem.Builder addDataItemsBuilder(int index) { return getDataItemsFieldBuilder() .addBuilder(index, com.google.cloud.datalabeling.v1beta1.DataItem.getDefaultInstance()); } /** * * * <pre> * The list of data items to return. * </pre> * * <code>repeated .google.cloud.datalabeling.v1beta1.DataItem data_items = 1;</code> */ public java.util.List<com.google.cloud.datalabeling.v1beta1.DataItem.Builder> getDataItemsBuilderList() { return getDataItemsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.DataItem, com.google.cloud.datalabeling.v1beta1.DataItem.Builder, com.google.cloud.datalabeling.v1beta1.DataItemOrBuilder> getDataItemsFieldBuilder() { if (dataItemsBuilder_ == null) { dataItemsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datalabeling.v1beta1.DataItem, com.google.cloud.datalabeling.v1beta1.DataItem.Builder, com.google.cloud.datalabeling.v1beta1.DataItemOrBuilder>( dataItems_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dataItems_ = null; } return dataItemsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datalabeling.v1beta1.ListDataItemsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.ListDataItemsResponse) private static final com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse(); } public static com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDataItemsResponse> PARSER = new com.google.protobuf.AbstractParser<ListDataItemsResponse>() { @java.lang.Override public ListDataItemsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListDataItemsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDataItemsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDataItemsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/pinot
36,309
pinot-core/src/test/java/org/apache/pinot/queries/GapfillQueriesScalabilityTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.queries; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.pinot.common.response.broker.BrokerResponseNative; import org.apache.pinot.common.response.broker.ResultTable; import org.apache.pinot.segment.local.indexsegment.immutable.ImmutableSegmentLoader; import org.apache.pinot.segment.local.segment.creator.impl.SegmentIndexCreationDriverImpl; import org.apache.pinot.segment.local.segment.readers.GenericRowRecordReader; import org.apache.pinot.segment.spi.ImmutableSegment; import org.apache.pinot.segment.spi.IndexSegment; import org.apache.pinot.segment.spi.creator.SegmentGeneratorConfig; import org.apache.pinot.spi.config.table.TableConfig; import org.apache.pinot.spi.config.table.TableType; import org.apache.pinot.spi.data.DateTimeFormatSpec; import org.apache.pinot.spi.data.DateTimeGranularitySpec; import org.apache.pinot.spi.data.FieldSpec.DataType; import org.apache.pinot.spi.data.Schema; import org.apache.pinot.spi.data.readers.GenericRow; import org.apache.pinot.spi.utils.ReadMode; import org.apache.pinot.spi.utils.builder.TableConfigBuilder; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Scalability Queries test for Gapfill queries. */ public class GapfillQueriesScalabilityTest extends BaseQueriesTest { private static final File INDEX_DIR = new File(FileUtils.getTempDirectory(), "PostAggregationGapfillQueriesTest"); private static final String RAW_TABLE_NAME = "parkingData"; private static final String SEGMENT_NAME = "testSegment"; private static final int NUM_LOTS = 400; private static final String IS_OCCUPIED_COLUMN = "isOccupied"; private static final String LEVEL_ID_COLUMN = "levelId"; private static final String LOT_ID_COLUMN = "lotId"; private static final String EVENT_TIME_COLUMN = "eventTime"; private static final Schema SCHEMA = new Schema.SchemaBuilder().addSingleValueDimension(IS_OCCUPIED_COLUMN, DataType.INT) .addSingleValueDimension(LOT_ID_COLUMN, DataType.STRING) .addSingleValueDimension(LEVEL_ID_COLUMN, DataType.STRING) .addSingleValueDimension(EVENT_TIME_COLUMN, DataType.LONG) .setPrimaryKeyColumns(Arrays.asList(LOT_ID_COLUMN, EVENT_TIME_COLUMN)).build(); private static final TableConfig TABLE_CONFIG = new TableConfigBuilder(TableType.OFFLINE).setTableName(RAW_TABLE_NAME).build(); private IndexSegment _indexSegment; private List<IndexSegment> _indexSegments; @Override protected String getFilter() { // NOTE: Use a match all filter to switch between DictionaryBasedAggregationOperator and AggregationOperator return " WHERE eventTime >= 0"; } @Override protected IndexSegment getIndexSegment() { return _indexSegment; } @Override protected List<IndexSegment> getIndexSegments() { return _indexSegments; } GenericRow createRow(long time, int levelId, int lotId, boolean isOccupied) { GenericRow parkingRow = new GenericRow(); parkingRow.putValue(EVENT_TIME_COLUMN, time); parkingRow.putValue(LEVEL_ID_COLUMN, "Level_" + levelId); parkingRow.putValue(LOT_ID_COLUMN, "LotId_" + lotId); parkingRow.putValue(IS_OCCUPIED_COLUMN, isOccupied); return parkingRow; } @BeforeClass public void setUp() throws Exception { FileUtils.deleteDirectory(INDEX_DIR); List<GenericRow> records = new ArrayList<>(NUM_LOTS * 2); long start = 1636243200000L + 5000; for (int i = 0; i < 15; i++) { for (int j = 0; j < NUM_LOTS; j++) { for (int k = 0; k < 4; k++) { records.add(createRow(start + i * 3600_000, k, i * NUM_LOTS + j, true)); } } } start += 9 * 3600_000; for (int i = 0; i < 15; i++) { for (int j = 0; j < NUM_LOTS; j++) { for (int k = 0; k < 4; k++) { records.add(createRow(start + i * 3600_000, k, i * NUM_LOTS + j, false)); } } } start += 15 * 3600_000; for (int i = 0; i < 15; i++) { for (int j = 0; j < NUM_LOTS; j++) { for (int k = 0; k < 4; k++) { records.add(createRow(start + i * 3600_000, k, i * NUM_LOTS + j, true)); } } } start += 9 * 3600_000; for (int i = 0; i < 15; i++) { for (int j = 0; j < NUM_LOTS; j++) { for (int k = 0; k < 4; k++) { records.add(createRow(start + i * 3600_000, k, i * NUM_LOTS + j, false)); } } } SegmentGeneratorConfig segmentGeneratorConfig = new SegmentGeneratorConfig(TABLE_CONFIG, SCHEMA); segmentGeneratorConfig.setTableName(RAW_TABLE_NAME); segmentGeneratorConfig.setSegmentName(SEGMENT_NAME); segmentGeneratorConfig.setOutDir(INDEX_DIR.getPath()); SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl(); driver.init(segmentGeneratorConfig, new GenericRowRecordReader(records)); driver.build(); ImmutableSegment immutableSegment = ImmutableSegmentLoader.load(new File(INDEX_DIR, SEGMENT_NAME), ReadMode.mmap); _indexSegment = immutableSegment; _indexSegments = Arrays.asList(immutableSegment); } @Test public void datetimeconvertGapfillTestAggregateAggregateScalabilityTestCountWithLongTimeColumn() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:EPOCH"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("15:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, count(occupied) as occupied_slots_count " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:EPOCH', " + " '1636243200000', '1636416000000', '15:MINUTES'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:EPOCH', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); long [] expectedOccupiedSlotsCounts1 = new long []{ 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("1636243200000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { long firstTimeCol = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(firstTimeCol, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("1636329600000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { long firstTimeCol = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(firstTimeCol, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } } @Test public void datetimeconvertGapfillTestAggregateAggregateScalabilityTestCountWithStringTimeColumn() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("15:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, count(occupied) as occupied_slots_count " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', " + " '2021-11-07 00:00:00.000', '2021-11-09 00:00:00.000', '15:MINUTES'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); long [] expectedOccupiedSlotsCounts1 = new long []{ 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("2021-11-07 00:00:00.000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("2021-11-08 00:00:00.000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } } @Test public void datetimeconvertGapfillTestAggregateAggregateScalabilityTestSumAvgWithLongTimeColumn() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:EPOCH"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("15:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, SUM(occupied) as occupied_slots_count, AVG(occupied) " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:EPOCH', " + " '1636243200000', '1636416000000', '15:MINUTES'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:EPOCH', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); double [] expectedOccupiedSlotsCounts1 = new double []{ 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("1636243200000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { long timeStamp = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("1636329600000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { long timeStamp = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } } @Test public void datetimeconvertGapfillTestAggregateAggregateScalabilityTestSumAvgWithStringTimeColumn() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("15:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, SUM(occupied) as occupied_slots_count, AVG(occupied) " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', " + " '2021-11-07 00:00:00.000', '2021-11-09 00:00:00.000', '15:MINUTES'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); double [] expectedOccupiedSlotsCounts1 = new double []{ 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 3200, 3200, 3200, 3200, 4800, 4800, 4800, 4800, 6400, 6400, 6400, 6400, 8000, 8000, 8000, 8000, 9600, 9600, 9600, 9600, 11200, 11200, 11200, 11200, 12800, 12800, 12800, 12800, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 14400, 12800, 12800, 12800, 12800, 11200, 11200, 11200, 11200, 9600, 9600, 9600, 9600, 8000, 8000, 8000, 8000, 6400, 6400, 6400, 6400, 4800, 4800, 4800, 4800, 3200, 3200, 3200, 3200, 1600, 1600, 1600, 1600}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("2021-11-07 00:00:00.000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("2021-11-08 00:00:00.000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } } @Test public void datetimeconvertGapfillTestAggAggScalabilityTestCountWithLongTimeColumnWithTimeBucketAggregation() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:EPOCH"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("60:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, count(occupied) as occupied_slots_count " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:EPOCH', " + " '1636243200000', '1636416000000', '15:MINUTES', '1:HOURS'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:EPOCH', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); long [] expectedOccupiedSlotsCounts1 = new long []{ 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400, 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("1636243200000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { long firstTimeCol = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(firstTimeCol, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("1636329600000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { long firstTimeCol = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(firstTimeCol, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } } @Test public void datetimeconvertGapfillTestAggAggScalabilityTestCountWithStringTimeColumnWithTimeBucketAggregation() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("60:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, count(occupied) as occupied_slots_count " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', " + " '2021-11-07 00:00:00.000', '2021-11-09 00:00:00.000', '15:MINUTES', '1:HOURS'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); long [] expectedOccupiedSlotsCounts1 = new long []{ 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400, 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("2021-11-07 00:00:00.000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("2021-11-08 00:00:00.000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); start += dateTimeGranularity.granularityToMillis(); } } @Test public void datetimeconvertGapfillTestAggAggScalabilityTestSumAvgWithLongTimeColumnWithTimeBucketAggregation() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:EPOCH"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("60:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, SUM(occupied) as occupied_slots_count, AVG(occupied) " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:EPOCH', " + " '1636243200000', '1636416000000', '15:MINUTES', '1:HOURS'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:EPOCH', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); double [] expectedOccupiedSlotsCounts1 = new double []{ 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400, 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("1636243200000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { long timeStamp = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("1636329600000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { long timeStamp = (Long) gapFillRows1.get(i)[0]; Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } } @Test public void datetimeconvertGapfillTestAggAggScalabilityTestSumAvgWithStringTimeColumnWithTimeBucketAggregation() { DateTimeFormatSpec dateTimeFormatter = new DateTimeFormatSpec("1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS"); DateTimeGranularitySpec dateTimeGranularity = new DateTimeGranularitySpec("60:MINUTES"); long start; String gapfillQuery1 = "SELECT " + "time_col, SUM(occupied) as occupied_slots_count, AVG(occupied) " + "FROM (" + " SELECT GapFill(time_col, " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', " + " '2021-11-07 00:00:00.000', '2021-11-09 00:00:00.000', '15:MINUTES', '1:HOURS'," + " FILL(occupied, 'FILL_PREVIOUS_VALUE'), TIMESERIESON(levelId, lotId)) AS time_col," + " occupied, lotId, levelId" + " FROM (" + " SELECT DATETIMECONVERT(eventTime, '1:MILLISECONDS:EPOCH', " + " '1:MILLISECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss.SSS', '15:MINUTES') AS time_col," + " lastWithTime(isOccupied, eventTime, 'INT') as occupied, lotId, levelId" + " FROM parkingData " + " WHERE eventTime >= 1636243200000 AND eventTime < 1636416000000 " + " GROUP BY time_col, levelId, lotId " + " ORDER BY time_col " + " LIMIT 200000000 " + " ) " + " LIMIT 2000000000 " + ") " + " where occupied = 1 " + " GROUP BY time_col " + " LIMIT 200000000 "; BrokerResponseNative gapfillBrokerResponse1 = getBrokerResponse(gapfillQuery1); double [] expectedOccupiedSlotsCounts1 = new double []{ 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400, 6400, 12800, 19200, 25600, 32000, 38400, 44800, 51200, 57600, 57600, 57600, 57600, 57600, 57600, 57600, 51200, 44800, 38400, 32000, 25600, 19200, 12800, 6400}; ResultTable gapFillResultTable1 = gapfillBrokerResponse1.getResultTable(); List<Object[]> gapFillRows1 = gapFillResultTable1.getRows(); Assert.assertEquals(gapFillRows1.size(), expectedOccupiedSlotsCounts1.length); start = dateTimeFormatter.fromFormatToMillis("2021-11-07 00:00:00.000"); for (int i = 0; i < expectedOccupiedSlotsCounts1.length / 2; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } start = dateTimeFormatter.fromFormatToMillis("2021-11-08 00:00:00.000"); for (int i = expectedOccupiedSlotsCounts1.length / 2; i < expectedOccupiedSlotsCounts1.length; i++) { String firstTimeCol = (String) gapFillRows1.get(i)[0]; long timeStamp = dateTimeFormatter.fromFormatToMillis(firstTimeCol); Assert.assertEquals(timeStamp, start); Assert.assertEquals(expectedOccupiedSlotsCounts1[i], gapFillRows1.get(i)[1]); Assert.assertEquals(1.0, gapFillRows1.get(i)[2]); start += dateTimeGranularity.granularityToMillis(); } } @AfterClass public void tearDown() throws IOException { _indexSegment.destroy(); FileUtils.deleteDirectory(INDEX_DIR); } }
googleapis/google-api-java-client-services
36,616
clients/google-api-services-compute/alpha/1.31.0/com/google/api/services/compute/model/Firewall.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Represents a Firewall Rule resource. Firewall rules allow or deny ingress traffic to, and egress * traffic from your instances. For more information, read Firewall rules. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Firewall extends com.google.api.client.json.GenericJson { /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Allowed> allowed; static { // hack to force ProGuard to consider Allowed used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Allowed.class); } /** * [Output Only] Creation timestamp in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Denied> denied; static { // hack to force ProGuard to consider Denied used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Denied.class); } /** * An optional description of this resource. Provide this field when you create the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Both * IPv4 and IPv6 are supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinationRanges; /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String direction; /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean disabled; /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableLogging; /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Cloud Logging. * The value may be {@code null}. */ @com.google.api.client.util.Key private FirewallLogConfig logConfig; /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network - * projects/myproject/global/networks/my-network - global/networks/default * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String network; /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer priority; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] Server-defined URL for this resource with the resource id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLinkWithId; /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Both IPv4 and IPv6 are supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceRanges; /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceServiceAccounts; /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceTags; /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetServiceAccounts; /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetTags; /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @return value or {@code null} for none */ public java.util.List<Allowed> getAllowed() { return allowed; } /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @param allowed allowed or {@code null} for none */ public Firewall setAllowed(java.util.List<Allowed> allowed) { this.allowed = allowed; return this; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Firewall setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @return value or {@code null} for none */ public java.util.List<Denied> getDenied() { return denied; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @param denied denied or {@code null} for none */ public Firewall setDenied(java.util.List<Denied> denied) { this.denied = denied; return this; } /** * An optional description of this resource. Provide this field when you create the resource. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * An optional description of this resource. Provide this field when you create the resource. * @param description description or {@code null} for none */ public Firewall setDescription(java.lang.String description) { this.description = description; return this; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Both * IPv4 and IPv6 are supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getDestinationRanges() { return destinationRanges; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Both * IPv4 and IPv6 are supported. * @param destinationRanges destinationRanges or {@code null} for none */ public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) { this.destinationRanges = destinationRanges; return this; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @return value or {@code null} for none */ public java.lang.String getDirection() { return direction; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @param direction direction or {@code null} for none */ public Firewall setDirection(java.lang.String direction) { this.direction = direction; return this; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @return value or {@code null} for none */ public java.lang.Boolean getDisabled() { return disabled; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @param disabled disabled or {@code null} for none */ public Firewall setDisabled(java.lang.Boolean disabled) { this.disabled = disabled; return this; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging. * @return value or {@code null} for none */ public java.lang.Boolean getEnableLogging() { return enableLogging; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging. * @param enableLogging enableLogging or {@code null} for none */ public Firewall setEnableLogging(java.lang.Boolean enableLogging) { this.enableLogging = enableLogging; return this; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @param id id or {@code null} for none */ public Firewall setId(java.math.BigInteger id) { this.id = id; return this; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @param kind kind or {@code null} for none */ public Firewall setKind(java.lang.String kind) { this.kind = kind; return this; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Cloud Logging. * @return value or {@code null} for none */ public FirewallLogConfig getLogConfig() { return logConfig; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Cloud Logging. * @param logConfig logConfig or {@code null} for none */ public Firewall setLogConfig(FirewallLogConfig logConfig) { this.logConfig = logConfig; return this; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @param name name or {@code null} for none */ public Firewall setName(java.lang.String name) { this.name = name; return this; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network - * projects/myproject/global/networks/my-network - global/networks/default * @return value or {@code null} for none */ public java.lang.String getNetwork() { return network; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network - * projects/myproject/global/networks/my-network - global/networks/default * @param network network or {@code null} for none */ public Firewall setNetwork(java.lang.String network) { this.network = network; return this; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @return value or {@code null} for none */ public java.lang.Integer getPriority() { return priority; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @param priority priority or {@code null} for none */ public Firewall setPriority(java.lang.Integer priority) { this.priority = priority; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Firewall setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @return value or {@code null} for none */ public java.lang.String getSelfLinkWithId() { return selfLinkWithId; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @param selfLinkWithId selfLinkWithId or {@code null} for none */ public Firewall setSelfLinkWithId(java.lang.String selfLinkWithId) { this.selfLinkWithId = selfLinkWithId; return this; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Both IPv4 and IPv6 are supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceRanges() { return sourceRanges; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Both IPv4 and IPv6 are supported. * @param sourceRanges sourceRanges or {@code null} for none */ public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) { this.sourceRanges = sourceRanges; return this; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceServiceAccounts() { return sourceServiceAccounts; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none */ public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) { this.sourceServiceAccounts = sourceServiceAccounts; return this; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceTags() { return sourceTags; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @param sourceTags sourceTags or {@code null} for none */ public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) { this.sourceTags = sourceTags; return this; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetServiceAccounts() { return targetServiceAccounts; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @param targetServiceAccounts targetServiceAccounts or {@code null} for none */ public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) { this.targetServiceAccounts = targetServiceAccounts; return this; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetTags() { return targetTags; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @param targetTags targetTags or {@code null} for none */ public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) { this.targetTags = targetTags; return this; } @Override public Firewall set(String fieldName, Object value) { return (Firewall) super.set(fieldName, value); } @Override public Firewall clone() { return (Firewall) super.clone(); } /** * Model definition for FirewallAllowed. */ public static final class Allowed extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. Example inputs include: ["22"], ["80","443"], and * ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Allowed setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. Example inputs include: ["22"], ["80","443"], and * ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. Example inputs include: ["22"], ["80","443"], and * ["12345-12349"]. * @param ports ports or {@code null} for none */ public Allowed setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Allowed set(String fieldName, Object value) { return (Allowed) super.set(fieldName, value); } @Override public Allowed clone() { return (Allowed) super.clone(); } } /** * Model definition for FirewallDenied. */ public static final class Denied extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. Example inputs include: ["22"], ["80","443"], and * ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Denied setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. Example inputs include: ["22"], ["80","443"], and * ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. Example inputs include: ["22"], ["80","443"], and * ["12345-12349"]. * @param ports ports or {@code null} for none */ public Denied setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Denied set(String fieldName, Object value) { return (Denied) super.set(fieldName, value); } @Override public Denied clone() { return (Denied) super.clone(); } } }
googleapis/google-cloud-java
36,307
java-appengine-admin/proto-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/UpdateVersionRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/appengine/v1/appengine.proto // Protobuf Java Version: 3.25.8 package com.google.appengine.v1; /** * * * <pre> * Request message for `Versions.UpdateVersion`. * </pre> * * Protobuf type {@code google.appengine.v1.UpdateVersionRequest} */ public final class UpdateVersionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.appengine.v1.UpdateVersionRequest) UpdateVersionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateVersionRequest.newBuilder() to construct. private UpdateVersionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateVersionRequest() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateVersionRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateVersionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateVersionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.appengine.v1.UpdateVersionRequest.class, com.google.appengine.v1.UpdateVersionRequest.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/services/default/versions/1`. * </pre> * * <code>string name = 1;</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/services/default/versions/1`. * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VERSION_FIELD_NUMBER = 2; private com.google.appengine.v1.Version version_; /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> * * @return Whether the version field is set. */ @java.lang.Override public boolean hasVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> * * @return The version. */ @java.lang.Override public com.google.appengine.v1.Version getVersion() { return version_ == null ? com.google.appengine.v1.Version.getDefaultInstance() : version_; } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ @java.lang.Override public com.google.appengine.v1.VersionOrBuilder getVersionOrBuilder() { return version_ == null ? com.google.appengine.v1.Version.getDefaultInstance() : version_; } public static final int UPDATE_MASK_FIELD_NUMBER = 3; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getVersion()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getUpdateMask()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getVersion()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getUpdateMask()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.appengine.v1.UpdateVersionRequest)) { return super.equals(obj); } com.google.appengine.v1.UpdateVersionRequest other = (com.google.appengine.v1.UpdateVersionRequest) obj; if (!getName().equals(other.getName())) return false; if (hasVersion() != other.hasVersion()) return false; if (hasVersion()) { if (!getVersion().equals(other.getVersion())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (hasVersion()) { hash = (37 * hash) + VERSION_FIELD_NUMBER; hash = (53 * hash) + getVersion().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.appengine.v1.UpdateVersionRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.appengine.v1.UpdateVersionRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.appengine.v1.UpdateVersionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.appengine.v1.UpdateVersionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.appengine.v1.UpdateVersionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for `Versions.UpdateVersion`. * </pre> * * Protobuf type {@code google.appengine.v1.UpdateVersionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.appengine.v1.UpdateVersionRequest) com.google.appengine.v1.UpdateVersionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateVersionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateVersionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.appengine.v1.UpdateVersionRequest.class, com.google.appengine.v1.UpdateVersionRequest.Builder.class); } // Construct using com.google.appengine.v1.UpdateVersionRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getVersionFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; version_ = null; if (versionBuilder_ != null) { versionBuilder_.dispose(); versionBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_UpdateVersionRequest_descriptor; } @java.lang.Override public com.google.appengine.v1.UpdateVersionRequest getDefaultInstanceForType() { return com.google.appengine.v1.UpdateVersionRequest.getDefaultInstance(); } @java.lang.Override public com.google.appengine.v1.UpdateVersionRequest build() { com.google.appengine.v1.UpdateVersionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.appengine.v1.UpdateVersionRequest buildPartial() { com.google.appengine.v1.UpdateVersionRequest result = new com.google.appengine.v1.UpdateVersionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.appengine.v1.UpdateVersionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.version_ = versionBuilder_ == null ? version_ : versionBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.appengine.v1.UpdateVersionRequest) { return mergeFrom((com.google.appengine.v1.UpdateVersionRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.appengine.v1.UpdateVersionRequest other) { if (other == com.google.appengine.v1.UpdateVersionRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasVersion()) { mergeVersion(other.getVersion()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getVersionFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/services/default/versions/1`. * </pre> * * <code>string name = 1;</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/services/default/versions/1`. * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/services/default/versions/1`. * </pre> * * <code>string name = 1;</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/services/default/versions/1`. * </pre> * * <code>string name = 1;</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Name of the resource to update. Example: * `apps/myapp/services/default/versions/1`. * </pre> * * <code>string name = 1;</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.appengine.v1.Version version_; private com.google.protobuf.SingleFieldBuilderV3< com.google.appengine.v1.Version, com.google.appengine.v1.Version.Builder, com.google.appengine.v1.VersionOrBuilder> versionBuilder_; /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> * * @return Whether the version field is set. */ public boolean hasVersion() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> * * @return The version. */ public com.google.appengine.v1.Version getVersion() { if (versionBuilder_ == null) { return version_ == null ? com.google.appengine.v1.Version.getDefaultInstance() : version_; } else { return versionBuilder_.getMessage(); } } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ public Builder setVersion(com.google.appengine.v1.Version value) { if (versionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } version_ = value; } else { versionBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ public Builder setVersion(com.google.appengine.v1.Version.Builder builderForValue) { if (versionBuilder_ == null) { version_ = builderForValue.build(); } else { versionBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ public Builder mergeVersion(com.google.appengine.v1.Version value) { if (versionBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && version_ != null && version_ != com.google.appengine.v1.Version.getDefaultInstance()) { getVersionBuilder().mergeFrom(value); } else { version_ = value; } } else { versionBuilder_.mergeFrom(value); } if (version_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ public Builder clearVersion() { bitField0_ = (bitField0_ & ~0x00000002); version_ = null; if (versionBuilder_ != null) { versionBuilder_.dispose(); versionBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ public com.google.appengine.v1.Version.Builder getVersionBuilder() { bitField0_ |= 0x00000002; onChanged(); return getVersionFieldBuilder().getBuilder(); } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ public com.google.appengine.v1.VersionOrBuilder getVersionOrBuilder() { if (versionBuilder_ != null) { return versionBuilder_.getMessageOrBuilder(); } else { return version_ == null ? com.google.appengine.v1.Version.getDefaultInstance() : version_; } } /** * * * <pre> * A Version containing the updated resource. Only fields set in the field * mask will be updated. * </pre> * * <code>.google.appengine.v1.Version version = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.appengine.v1.Version, com.google.appengine.v1.Version.Builder, com.google.appengine.v1.VersionOrBuilder> getVersionFieldBuilder() { if (versionBuilder_ == null) { versionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.appengine.v1.Version, com.google.appengine.v1.Version.Builder, com.google.appengine.v1.VersionOrBuilder>( getVersion(), getParentForChildren(), isClean()); version_ = null; } return versionBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000004); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000004; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Standard field mask for the set of fields to be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.appengine.v1.UpdateVersionRequest) } // @@protoc_insertion_point(class_scope:google.appengine.v1.UpdateVersionRequest) private static final com.google.appengine.v1.UpdateVersionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.appengine.v1.UpdateVersionRequest(); } public static com.google.appengine.v1.UpdateVersionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateVersionRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateVersionRequest>() { @java.lang.Override public UpdateVersionRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UpdateVersionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateVersionRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.appengine.v1.UpdateVersionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/flink
36,602
flink-queryable-state/flink-queryable-state-runtime/src/test/java/org/apache/flink/queryablestate/network/KvStateServerHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.queryablestate.network; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.state.ValueState; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.common.typeutils.base.IntSerializer; import org.apache.flink.api.common.typeutils.base.LongSerializer; import org.apache.flink.api.common.typeutils.base.StringSerializer; import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer; import org.apache.flink.core.fs.CloseableRegistry; import org.apache.flink.metrics.groups.UnregisteredMetricsGroup; import org.apache.flink.queryablestate.KvStateID; import org.apache.flink.queryablestate.client.VoidNamespace; import org.apache.flink.queryablestate.client.VoidNamespaceSerializer; import org.apache.flink.queryablestate.client.state.serialization.KvStateSerializer; import org.apache.flink.queryablestate.exceptions.UnknownKeyOrNamespaceException; import org.apache.flink.queryablestate.exceptions.UnknownKvStateIdException; import org.apache.flink.queryablestate.messages.KvStateInternalRequest; import org.apache.flink.queryablestate.messages.KvStateResponse; import org.apache.flink.queryablestate.network.messages.MessageSerializer; import org.apache.flink.queryablestate.network.messages.MessageType; import org.apache.flink.queryablestate.network.messages.RequestFailure; import org.apache.flink.queryablestate.network.stats.AtomicKvStateRequestStats; import org.apache.flink.queryablestate.network.stats.DisabledKvStateRequestStats; import org.apache.flink.queryablestate.network.stats.KvStateRequestStats; import org.apache.flink.queryablestate.server.KvStateServerHandler; import org.apache.flink.queryablestate.server.KvStateServerImpl; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.operators.testutils.DummyEnvironment; import org.apache.flink.runtime.query.KvStateRegistry; import org.apache.flink.runtime.query.KvStateRegistryListener; import org.apache.flink.runtime.query.TaskKvStateRegistry; import org.apache.flink.runtime.state.AbstractKeyedStateBackend; import org.apache.flink.runtime.state.AbstractStateBackend; import org.apache.flink.runtime.state.KeyGroupRange; import org.apache.flink.runtime.state.KeyedStateBackend; import org.apache.flink.runtime.state.KeyedStateBackendParametersImpl; import org.apache.flink.runtime.state.hashmap.HashMapStateBackend; import org.apache.flink.runtime.state.internal.InternalKvState; import org.apache.flink.runtime.state.ttl.TtlTimeProvider; import org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf; import org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled; import org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandler; import org.apache.flink.shaded.netty4.io.netty.channel.embedded.EmbeddedChannel; import org.apache.flink.shaded.netty4.io.netty.handler.codec.LengthFieldBasedFrameDecoder; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.net.InetAddress; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link KvStateServerHandler}. */ @Disabled( "KvStateServerHandlerTest is unstable. See FLINK-13553 for more information. Since the community " + "does not have time to work on QS, we decided to temporarily ignore this test case in order" + "to maintain build stability.") class KvStateServerHandlerTest { private static KvStateServerImpl testServer; private static final long READ_TIMEOUT_MILLIS = 10000L; @BeforeAll static void setup() { try { testServer = new KvStateServerImpl( InetAddress.getLocalHost().getHostName(), Collections.singletonList(0).iterator(), 1, 1, new KvStateRegistry(), new DisabledKvStateRequestStats()); testServer.start(); } catch (Throwable e) { e.printStackTrace(); } } @AfterAll static void tearDown() throws Exception { testServer.shutdown(); } /** Tests a simple successful query via an EmbeddedChannel. */ @Test void testSimpleQuery() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); // Register state ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE); desc.setQueryable("vanilla"); int numKeyGroups = 1; AbstractStateBackend abstractBackend = new HashMapStateBackend(); DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0); dummyEnv.setKvStateRegistry(registry); AbstractKeyedStateBackend<Integer> backend = createKeyedStateBackend(registry, numKeyGroups, abstractBackend, dummyEnv); final TestRegistryListener registryListener = new TestRegistryListener(); registry.registerListener(dummyEnv.getJobID(), registryListener); // Update the KvState and request it int expectedValue = 712828289; int key = 99812822; backend.setCurrentKey(key); ValueState<Integer> state = backend.getPartitionedState( VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc); state.update(expectedValue); byte[] serializedKeyAndNamespace = KvStateSerializer.serializeKeyAndNamespace( key, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE); long requestId = Integer.MAX_VALUE + 182828L; assertThat(registryListener.registrationName).isEqualTo("vanilla"); KvStateInternalRequest request = new KvStateInternalRequest(registryListener.kvStateId, serializedKeyAndNamespace); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), requestId, request); // Write the request and wait for the response channel.writeInbound(serRequest); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_RESULT); long deserRequestId = MessageSerializer.getRequestId(buf); KvStateResponse response = serializer.deserializeResponse(buf); buf.release(); assertThat(deserRequestId).isEqualTo(requestId); int actualValue = KvStateSerializer.deserializeValue(response.getContent(), IntSerializer.INSTANCE); assertThat(actualValue).isEqualTo(expectedValue); assertThat(stats.getNumRequests()).isEqualTo(1).withFailMessage(stats.toString()); // Wait for async successful request report long deadline = System.nanoTime() + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS); while (stats.getNumSuccessful() != 1L && System.nanoTime() <= deadline) { Thread.sleep(10L); } assertThat(stats.getNumSuccessful()).isEqualTo(1L).withFailMessage(stats.toString()); } /** * Tests the failure response with {@link UnknownKvStateIdException} as cause on queries for * unregistered KvStateIDs. */ @Test void testQueryUnknownKvStateID() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); long requestId = Integer.MAX_VALUE + 182828L; KvStateInternalRequest request = new KvStateInternalRequest(new KvStateID(), new byte[0]); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), requestId, request); // Write the request and wait for the response channel.writeInbound(serRequest); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_FAILURE); RequestFailure response = MessageSerializer.deserializeRequestFailure(buf); buf.release(); assertThat(response.getRequestId()).isEqualTo(requestId); assertThat(response.getCause()) .isInstanceOf(UnknownKvStateIdException.class) .withFailMessage("Did not respond with expected failure cause"); assertThat(stats.getNumRequests()).isEqualTo(1L); assertThat(stats.getNumFailed()).isEqualTo(1L); } /** * Tests the failure response with {@link UnknownKeyOrNamespaceException} as cause on queries * for non-existing keys. */ @Test void testQueryUnknownKey() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); int numKeyGroups = 1; AbstractStateBackend abstractBackend = new HashMapStateBackend(); DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0); dummyEnv.setKvStateRegistry(registry); KeyedStateBackend<Integer> backend = createKeyedStateBackend(registry, numKeyGroups, abstractBackend, dummyEnv); final TestRegistryListener registryListener = new TestRegistryListener(); registry.registerListener(dummyEnv.getJobID(), registryListener); // Register state ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE); desc.setQueryable("vanilla"); backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc); byte[] serializedKeyAndNamespace = KvStateSerializer.serializeKeyAndNamespace( 1238283, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE); long requestId = Integer.MAX_VALUE + 22982L; assertThat(registryListener.registrationName).isEqualTo("vanilla"); KvStateInternalRequest request = new KvStateInternalRequest(registryListener.kvStateId, serializedKeyAndNamespace); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), requestId, request); // Write the request and wait for the response channel.writeInbound(serRequest); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_FAILURE); RequestFailure response = MessageSerializer.deserializeRequestFailure(buf); buf.release(); assertThat(response.getRequestId()).isEqualTo(requestId); assertThat(response.getCause()) .isInstanceOf(UnknownKeyOrNamespaceException.class) .withFailMessage("Did not respond with expected failure cause"); assertThat(stats.getNumRequests()).isEqualTo(1L); assertThat(stats.getNumFailed()).isEqualTo(1L); } /** * Tests the failure response on a failure on the {@link * InternalKvState#getSerializedValue(byte[], TypeSerializer, TypeSerializer, TypeSerializer)} * call. */ @Test void testFailureOnGetSerializedValue() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); // Failing KvState InternalKvState<Integer, VoidNamespace, Long> kvState = new InternalKvState<Integer, VoidNamespace, Long>() { @Override public TypeSerializer<Integer> getKeySerializer() { return IntSerializer.INSTANCE; } @Override public TypeSerializer<VoidNamespace> getNamespaceSerializer() { return VoidNamespaceSerializer.INSTANCE; } @Override public TypeSerializer<Long> getValueSerializer() { return LongSerializer.INSTANCE; } @Override public void setCurrentNamespace(VoidNamespace namespace) { // do nothing } @Override public byte[] getSerializedValue( final byte[] serializedKeyAndNamespace, final TypeSerializer<Integer> safeKeySerializer, final TypeSerializer<VoidNamespace> safeNamespaceSerializer, final TypeSerializer<Long> safeValueSerializer) throws Exception { throw new RuntimeException("Expected test Exception"); } @Override public StateIncrementalVisitor<Integer, VoidNamespace, Long> getStateIncrementalVisitor(int recommendedMaxNumberOfReturnedRecords) { throw new UnsupportedOperationException(); } @Override public void clear() {} }; KvStateID kvStateId = registry.registerKvState( new JobID(), new JobVertexID(), new KeyGroupRange(0, 0), "vanilla", kvState, getClass().getClassLoader()); KvStateInternalRequest request = new KvStateInternalRequest(kvStateId, new byte[0]); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), 282872L, request); // Write the request and wait for the response channel.writeInbound(serRequest); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_FAILURE); RequestFailure response = MessageSerializer.deserializeRequestFailure(buf); buf.release(); assertThat(response.getCause().getMessage()).contains("Expected test Exception"); assertThat(stats.getNumRequests()).isEqualTo(1L); assertThat(stats.getNumFailed()).isEqualTo(1L); } /** Tests that the channel is closed if an Exception reaches the channel handler. */ @Test void testCloseChannelOnExceptionCaught() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(handler); channel.pipeline().fireExceptionCaught(new RuntimeException("Expected test Exception")); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.SERVER_FAILURE); Throwable response = MessageSerializer.deserializeServerFailure(buf); buf.release(); assertThat(response.getMessage()).contains("Expected test Exception"); channel.closeFuture().await(READ_TIMEOUT_MILLIS); assertThat(channel.isActive()).isFalse(); } /** * Tests the failure response on a rejected execution, because the query executor has been * closed. */ @Test void testQueryExecutorShutDown() throws Throwable { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); KvStateServerImpl localTestServer = new KvStateServerImpl( InetAddress.getLocalHost().getHostName(), Collections.singletonList(0).iterator(), 1, 1, new KvStateRegistry(), new DisabledKvStateRequestStats()); localTestServer.start(); localTestServer.shutdown(); assertThat(localTestServer.getQueryExecutor().isTerminated()).isTrue(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(localTestServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); int numKeyGroups = 1; AbstractStateBackend abstractBackend = new HashMapStateBackend(); DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0); dummyEnv.setKvStateRegistry(registry); KeyedStateBackend<Integer> backend = createKeyedStateBackend(registry, numKeyGroups, abstractBackend, dummyEnv); final TestRegistryListener registryListener = new TestRegistryListener(); registry.registerListener(dummyEnv.getJobID(), registryListener); // Register state ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE); desc.setQueryable("vanilla"); backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc); assertThat(registryListener.registrationName).isEqualTo("vanilla"); KvStateInternalRequest request = new KvStateInternalRequest(registryListener.kvStateId, new byte[0]); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), 282872L, request); // Write the request and wait for the response channel.writeInbound(serRequest); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_FAILURE); RequestFailure response = MessageSerializer.deserializeRequestFailure(buf); buf.release(); assertThat(response.getCause().getMessage()).contains("RejectedExecutionException"); assertThat(stats.getNumRequests()).isEqualTo(1L); assertThat(stats.getNumFailed()).isEqualTo(1L); localTestServer.shutdown(); } /** Tests response on unexpected messages. */ @Test void testUnexpectedMessage() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); // Write the request and wait for the response ByteBuf unexpectedMessage = Unpooled.buffer(8); unexpectedMessage.writeInt(4); unexpectedMessage.writeInt(123238213); channel.writeInbound(unexpectedMessage); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.SERVER_FAILURE); Throwable response = MessageSerializer.deserializeServerFailure(buf); buf.release(); assertThat(stats.getNumRequests()).isEqualTo(0L); assertThat(stats.getNumFailed()).isEqualTo(0L); KvStateResponse stateResponse = new KvStateResponse(new byte[0]); unexpectedMessage = MessageSerializer.serializeResponse(channel.alloc(), 192L, stateResponse); channel.writeInbound(unexpectedMessage); buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.SERVER_FAILURE); response = MessageSerializer.deserializeServerFailure(buf); buf.release(); assertThat(response) .isInstanceOf(IllegalArgumentException.class) .withFailMessage("Unexpected failure cause " + response.getClass().getName()); assertThat(stats.getNumRequests()).isEqualTo(0L); assertThat(stats.getNumFailed()).isEqualTo(0L); } /** Tests that incoming buffer instances are recycled. */ @Test void testIncomingBufferIsRecycled() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); KvStateInternalRequest request = new KvStateInternalRequest(new KvStateID(), new byte[0]); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), 282872L, request); assertThat(serRequest.refCnt()).isEqualTo(1L); // Write regular request channel.writeInbound(serRequest); assertThat(serRequest.refCnt()).isEqualTo(0L).withFailMessage("Buffer not recycled"); // Write unexpected msg ByteBuf unexpected = channel.alloc().buffer(8); unexpected.writeInt(4); unexpected.writeInt(4); assertThat(unexpected.refCnt()).isEqualTo(1L); channel.writeInbound(unexpected); assertThat(unexpected.refCnt()).isEqualTo(0L).withFailMessage("Buffer not recycled"); channel.finishAndReleaseAll(); } /** Tests the failure response if the serializers don't match. */ @Test void testSerializerMismatch() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); int numKeyGroups = 1; AbstractStateBackend abstractBackend = new HashMapStateBackend(); DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0); dummyEnv.setKvStateRegistry(registry); AbstractKeyedStateBackend<Integer> backend = createKeyedStateBackend(registry, numKeyGroups, abstractBackend, dummyEnv); final TestRegistryListener registryListener = new TestRegistryListener(); registry.registerListener(dummyEnv.getJobID(), registryListener); // Register state ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE); desc.setQueryable("vanilla"); ValueState<Integer> state = backend.getPartitionedState( VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc); int key = 99812822; // Update the KvState backend.setCurrentKey(key); state.update(712828289); byte[] wrongKeyAndNamespace = KvStateSerializer.serializeKeyAndNamespace( "wrong-key-type", StringSerializer.INSTANCE, "wrong-namespace-type", StringSerializer.INSTANCE); byte[] wrongNamespace = KvStateSerializer.serializeKeyAndNamespace( key, IntSerializer.INSTANCE, "wrong-namespace-type", StringSerializer.INSTANCE); assertThat(registryListener.registrationName).isEqualTo("vanilla"); KvStateInternalRequest request = new KvStateInternalRequest(registryListener.kvStateId, wrongKeyAndNamespace); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), 182828L, request); // Write the request and wait for the response channel.writeInbound(serRequest); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_FAILURE); RequestFailure response = MessageSerializer.deserializeRequestFailure(buf); buf.release(); assertThat(response.getRequestId()).isEqualTo(182828L); assertThat(response.getCause().getMessage()).contains("IOException"); // Repeat with wrong namespace only request = new KvStateInternalRequest(registryListener.kvStateId, wrongNamespace); serRequest = MessageSerializer.serializeRequest(channel.alloc(), 182829L, request); // Write the request and wait for the response channel.writeInbound(serRequest); buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_FAILURE); response = MessageSerializer.deserializeRequestFailure(buf); buf.release(); assertThat(response.getRequestId()).isEqualTo(182829L); assertThat(response.getCause().getMessage()).contains("IOException"); assertThat(stats.getNumRequests()).isEqualTo(2L); assertThat(stats.getNumFailed()).isEqualTo(2L); } /** Tests that large responses are chunked. */ @Test void testChunkedResponse() throws Exception { KvStateRegistry registry = new KvStateRegistry(); KvStateRequestStats stats = new AtomicKvStateRequestStats(); MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); KvStateServerHandler handler = new KvStateServerHandler(testServer, registry, serializer, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); int numKeyGroups = 1; AbstractStateBackend abstractBackend = new HashMapStateBackend(); DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0); dummyEnv.setKvStateRegistry(registry); AbstractKeyedStateBackend<Integer> backend = createKeyedStateBackend(registry, numKeyGroups, abstractBackend, dummyEnv); final TestRegistryListener registryListener = new TestRegistryListener(); registry.registerListener(dummyEnv.getJobID(), registryListener); // Register state ValueStateDescriptor<byte[]> desc = new ValueStateDescriptor<>("any", BytePrimitiveArraySerializer.INSTANCE); desc.setQueryable("vanilla"); ValueState<byte[]> state = backend.getPartitionedState( VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc); // Update KvState byte[] bytes = new byte[2 * channel.config().getWriteBufferHighWaterMark()]; byte current = 0; for (int i = 0; i < bytes.length; i++) { bytes[i] = current++; } int key = 99812822; backend.setCurrentKey(key); state.update(bytes); // Request byte[] serializedKeyAndNamespace = KvStateSerializer.serializeKeyAndNamespace( key, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE); long requestId = Integer.MAX_VALUE + 182828L; assertThat(registryListener.registrationName).isEqualTo("vanilla"); KvStateInternalRequest request = new KvStateInternalRequest(registryListener.kvStateId, serializedKeyAndNamespace); ByteBuf serRequest = MessageSerializer.serializeRequest(channel.alloc(), requestId, request); // Write the request and wait for the response channel.writeInbound(serRequest); Object msg = readInboundBlocking(channel); assertThat(msg).isInstanceOf(ChunkedByteBuf.class).withFailMessage("Not ChunkedByteBuf"); ((ChunkedByteBuf) msg).close(); } // ------------------------------------------------------------------------ /** Queries the embedded channel for data. */ private Object readInboundBlocking(EmbeddedChannel channel) throws InterruptedException, TimeoutException { final long sleepMillis = 50L; long sleptMillis = 0L; Object msg = null; while (sleptMillis < READ_TIMEOUT_MILLIS && (msg = channel.readOutbound()) == null) { Thread.sleep(sleepMillis); sleptMillis += sleepMillis; } if (msg == null) { throw new TimeoutException(); } else { return msg; } } /** Frame length decoder (expected by the serialized messages). */ private ChannelHandler getFrameDecoder() { return new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4); } /** * A listener that keeps the last updated KvState information so that a test can retrieve it. */ static class TestRegistryListener implements KvStateRegistryListener { volatile JobVertexID jobVertexID; volatile KeyGroupRange keyGroupIndex; volatile String registrationName; volatile KvStateID kvStateId; @Override public void notifyKvStateRegistered( JobID jobId, JobVertexID jobVertexId, KeyGroupRange keyGroupRange, String registrationName, KvStateID kvStateId) { this.jobVertexID = jobVertexId; this.keyGroupIndex = keyGroupRange; this.registrationName = registrationName; this.kvStateId = kvStateId; } @Override public void notifyKvStateUnregistered( JobID jobId, JobVertexID jobVertexId, KeyGroupRange keyGroupRange, String registrationName) {} } private AbstractKeyedStateBackend<Integer> createKeyedStateBackend( KvStateRegistry registry, int numKeyGroups, AbstractStateBackend abstractBackend, DummyEnvironment dummyEnv) throws java.io.IOException { JobID jobID = dummyEnv.getJobID(); KeyGroupRange keyGroupRange = new KeyGroupRange(0, 0); TaskKvStateRegistry kvStateRegistry = registry.createTaskRegistry(dummyEnv.getJobID(), dummyEnv.getJobVertexId()); CloseableRegistry cancelStreamRegistry = new CloseableRegistry(); return abstractBackend.createKeyedStateBackend( new KeyedStateBackendParametersImpl<>( dummyEnv, jobID, "test_op", IntSerializer.INSTANCE, numKeyGroups, keyGroupRange, kvStateRegistry, TtlTimeProvider.DEFAULT, new UnregisteredMetricsGroup(), Collections.emptyList(), cancelStreamRegistry)); } }
googleapis/google-cloud-java
36,368
java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListDataItemsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1/dataset_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1; /** * * * <pre> * Response message for * [DatasetService.ListDataItems][google.cloud.aiplatform.v1.DatasetService.ListDataItems]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListDataItemsResponse} */ public final class ListDataItemsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListDataItemsResponse) ListDataItemsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDataItemsResponse.newBuilder() to construct. private ListDataItemsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDataItemsResponse() { dataItems_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDataItemsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1_ListDataItemsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1_ListDataItemsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListDataItemsResponse.class, com.google.cloud.aiplatform.v1.ListDataItemsResponse.Builder.class); } public static final int DATA_ITEMS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1.DataItem> dataItems_; /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1.DataItem> getDataItemsList() { return dataItems_; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1.DataItemOrBuilder> getDataItemsOrBuilderList() { return dataItems_; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ @java.lang.Override public int getDataItemsCount() { return dataItems_.size(); } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.DataItem getDataItems(int index) { return dataItems_.get(index); } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.DataItemOrBuilder getDataItemsOrBuilder(int index) { return dataItems_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The standard List next-page token. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * The standard List next-page token. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < dataItems_.size(); i++) { output.writeMessage(1, dataItems_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < dataItems_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dataItems_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1.ListDataItemsResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.ListDataItemsResponse other = (com.google.cloud.aiplatform.v1.ListDataItemsResponse) obj; if (!getDataItemsList().equals(other.getDataItemsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getDataItemsCount() > 0) { hash = (37 * hash) + DATA_ITEMS_FIELD_NUMBER; hash = (53 * hash) + getDataItemsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.aiplatform.v1.ListDataItemsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for * [DatasetService.ListDataItems][google.cloud.aiplatform.v1.DatasetService.ListDataItems]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListDataItemsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListDataItemsResponse) com.google.cloud.aiplatform.v1.ListDataItemsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1_ListDataItemsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1_ListDataItemsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListDataItemsResponse.class, com.google.cloud.aiplatform.v1.ListDataItemsResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.ListDataItemsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dataItemsBuilder_ == null) { dataItems_ = java.util.Collections.emptyList(); } else { dataItems_ = null; dataItemsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.DatasetServiceProto .internal_static_google_cloud_aiplatform_v1_ListDataItemsResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListDataItemsResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.ListDataItemsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.ListDataItemsResponse build() { com.google.cloud.aiplatform.v1.ListDataItemsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListDataItemsResponse buildPartial() { com.google.cloud.aiplatform.v1.ListDataItemsResponse result = new com.google.cloud.aiplatform.v1.ListDataItemsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1.ListDataItemsResponse result) { if (dataItemsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dataItems_ = java.util.Collections.unmodifiableList(dataItems_); bitField0_ = (bitField0_ & ~0x00000001); } result.dataItems_ = dataItems_; } else { result.dataItems_ = dataItemsBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1.ListDataItemsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1.ListDataItemsResponse) { return mergeFrom((com.google.cloud.aiplatform.v1.ListDataItemsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListDataItemsResponse other) { if (other == com.google.cloud.aiplatform.v1.ListDataItemsResponse.getDefaultInstance()) return this; if (dataItemsBuilder_ == null) { if (!other.dataItems_.isEmpty()) { if (dataItems_.isEmpty()) { dataItems_ = other.dataItems_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDataItemsIsMutable(); dataItems_.addAll(other.dataItems_); } onChanged(); } } else { if (!other.dataItems_.isEmpty()) { if (dataItemsBuilder_.isEmpty()) { dataItemsBuilder_.dispose(); dataItemsBuilder_ = null; dataItems_ = other.dataItems_; bitField0_ = (bitField0_ & ~0x00000001); dataItemsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDataItemsFieldBuilder() : null; } else { dataItemsBuilder_.addAllMessages(other.dataItems_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.aiplatform.v1.DataItem m = input.readMessage( com.google.cloud.aiplatform.v1.DataItem.parser(), extensionRegistry); if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.add(m); } else { dataItemsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.aiplatform.v1.DataItem> dataItems_ = java.util.Collections.emptyList(); private void ensureDataItemsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dataItems_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1.DataItem>(dataItems_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.DataItem, com.google.cloud.aiplatform.v1.DataItem.Builder, com.google.cloud.aiplatform.v1.DataItemOrBuilder> dataItemsBuilder_; /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.DataItem> getDataItemsList() { if (dataItemsBuilder_ == null) { return java.util.Collections.unmodifiableList(dataItems_); } else { return dataItemsBuilder_.getMessageList(); } } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public int getDataItemsCount() { if (dataItemsBuilder_ == null) { return dataItems_.size(); } else { return dataItemsBuilder_.getCount(); } } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public com.google.cloud.aiplatform.v1.DataItem getDataItems(int index) { if (dataItemsBuilder_ == null) { return dataItems_.get(index); } else { return dataItemsBuilder_.getMessage(index); } } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder setDataItems(int index, com.google.cloud.aiplatform.v1.DataItem value) { if (dataItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataItemsIsMutable(); dataItems_.set(index, value); onChanged(); } else { dataItemsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder setDataItems( int index, com.google.cloud.aiplatform.v1.DataItem.Builder builderForValue) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.set(index, builderForValue.build()); onChanged(); } else { dataItemsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder addDataItems(com.google.cloud.aiplatform.v1.DataItem value) { if (dataItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataItemsIsMutable(); dataItems_.add(value); onChanged(); } else { dataItemsBuilder_.addMessage(value); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder addDataItems(int index, com.google.cloud.aiplatform.v1.DataItem value) { if (dataItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataItemsIsMutable(); dataItems_.add(index, value); onChanged(); } else { dataItemsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder addDataItems(com.google.cloud.aiplatform.v1.DataItem.Builder builderForValue) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.add(builderForValue.build()); onChanged(); } else { dataItemsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder addDataItems( int index, com.google.cloud.aiplatform.v1.DataItem.Builder builderForValue) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.add(index, builderForValue.build()); onChanged(); } else { dataItemsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder addAllDataItems( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1.DataItem> values) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dataItems_); onChanged(); } else { dataItemsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder clearDataItems() { if (dataItemsBuilder_ == null) { dataItems_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dataItemsBuilder_.clear(); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public Builder removeDataItems(int index) { if (dataItemsBuilder_ == null) { ensureDataItemsIsMutable(); dataItems_.remove(index); onChanged(); } else { dataItemsBuilder_.remove(index); } return this; } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public com.google.cloud.aiplatform.v1.DataItem.Builder getDataItemsBuilder(int index) { return getDataItemsFieldBuilder().getBuilder(index); } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public com.google.cloud.aiplatform.v1.DataItemOrBuilder getDataItemsOrBuilder(int index) { if (dataItemsBuilder_ == null) { return dataItems_.get(index); } else { return dataItemsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1.DataItemOrBuilder> getDataItemsOrBuilderList() { if (dataItemsBuilder_ != null) { return dataItemsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dataItems_); } } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public com.google.cloud.aiplatform.v1.DataItem.Builder addDataItemsBuilder() { return getDataItemsFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1.DataItem.getDefaultInstance()); } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public com.google.cloud.aiplatform.v1.DataItem.Builder addDataItemsBuilder(int index) { return getDataItemsFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1.DataItem.getDefaultInstance()); } /** * * * <pre> * A list of DataItems that matches the specified filter in the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.DataItem data_items = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.DataItem.Builder> getDataItemsBuilderList() { return getDataItemsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.DataItem, com.google.cloud.aiplatform.v1.DataItem.Builder, com.google.cloud.aiplatform.v1.DataItemOrBuilder> getDataItemsFieldBuilder() { if (dataItemsBuilder_ == null) { dataItemsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.DataItem, com.google.cloud.aiplatform.v1.DataItem.Builder, com.google.cloud.aiplatform.v1.DataItemOrBuilder>( dataItems_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dataItems_ = null; } return dataItemsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The standard List next-page token. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The standard List next-page token. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The standard List next-page token. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The standard List next-page token. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The standard List next-page token. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ListDataItemsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListDataItemsResponse) private static final com.google.cloud.aiplatform.v1.ListDataItemsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListDataItemsResponse(); } public static com.google.cloud.aiplatform.v1.ListDataItemsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDataItemsResponse> PARSER = new com.google.protobuf.AbstractParser<ListDataItemsResponse>() { @java.lang.Override public ListDataItemsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListDataItemsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDataItemsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListDataItemsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-api-java-client-services
36,610
clients/google-api-services-compute/alpha/1.30.1/com/google/api/services/compute/model/Firewall.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Represents a Firewall Rule resource. * * Firewall rules allow or deny ingress traffic to, and egress traffic from your instances. For more * information, read Firewall rules. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Firewall extends com.google.api.client.json.GenericJson { /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Allowed> allowed; static { // hack to force ProGuard to consider Allowed used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Allowed.class); } /** * [Output Only] Creation timestamp in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Denied> denied; static { // hack to force ProGuard to consider Denied used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Denied.class); } /** * An optional description of this resource. Provide this field when you create the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> destinationRanges; /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String direction; /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean disabled; /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableLogging; /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Cloud Logging. * The value may be {@code null}. */ @com.google.api.client.util.Key private FirewallLogConfig logConfig; /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String network; /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer priority; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] Server-defined URL for this resource with the resource id. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLinkWithId; /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceRanges; /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceServiceAccounts; /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sourceTags; /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetServiceAccounts; /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> targetTags; /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @return value or {@code null} for none */ public java.util.List<Allowed> getAllowed() { return allowed; } /** * The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a permitted connection. * @param allowed allowed or {@code null} for none */ public Firewall setAllowed(java.util.List<Allowed> allowed) { this.allowed = allowed; return this; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Output Only] Creation timestamp in RFC3339 text format. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Firewall setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @return value or {@code null} for none */ public java.util.List<Denied> getDenied() { return denied; } /** * The list of DENY rules specified by this firewall. Each rule specifies a protocol and port- * range tuple that describes a denied connection. * @param denied denied or {@code null} for none */ public Firewall setDenied(java.util.List<Denied> denied) { this.denied = denied; return this; } /** * An optional description of this resource. Provide this field when you create the resource. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * An optional description of this resource. Provide this field when you create the resource. * @param description description or {@code null} for none */ public Firewall setDescription(java.lang.String description) { this.description = description; return this; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getDestinationRanges() { return destinationRanges; } /** * If destination ranges are specified, the firewall rule applies only to traffic that has * destination IP address in these ranges. These ranges must be expressed in CIDR format. Only * IPv4 is supported. * @param destinationRanges destinationRanges or {@code null} for none */ public Firewall setDestinationRanges(java.util.List<java.lang.String> destinationRanges) { this.destinationRanges = destinationRanges; return this; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @return value or {@code null} for none */ public java.lang.String getDirection() { return direction; } /** * Direction of traffic to which this firewall applies, either `INGRESS` or `EGRESS`. The default * is `INGRESS`. For `INGRESS` traffic, you cannot specify the destinationRanges field, and for * `EGRESS` traffic, you cannot specify the sourceRanges or sourceTags fields. * @param direction direction or {@code null} for none */ public Firewall setDirection(java.lang.String direction) { this.direction = direction; return this; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @return value or {@code null} for none */ public java.lang.Boolean getDisabled() { return disabled; } /** * Denotes whether the firewall rule is disabled. When set to true, the firewall rule is not * enforced and the network behaves as if it did not exist. If this is unspecified, the firewall * rule will be enabled. * @param disabled disabled or {@code null} for none */ public Firewall setDisabled(java.lang.Boolean disabled) { this.disabled = disabled; return this; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging. * @return value or {@code null} for none */ public java.lang.Boolean getEnableLogging() { return enableLogging; } /** * Deprecated in favor of enable in LogConfig. This field denotes whether to enable logging for a * particular firewall rule. If logging is enabled, logs will be exported t Cloud Logging. * @param enableLogging enableLogging or {@code null} for none */ public Firewall setEnableLogging(java.lang.Boolean enableLogging) { this.enableLogging = enableLogging; return this; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the resource. This identifier is defined by the server. * @param id id or {@code null} for none */ public Firewall setId(java.math.BigInteger id) { this.id = id; return this; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always compute#firewall for firewall rules. * @param kind kind or {@code null} for none */ public Firewall setKind(java.lang.String kind) { this.kind = kind; return this; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Cloud Logging. * @return value or {@code null} for none */ public FirewallLogConfig getLogConfig() { return logConfig; } /** * This field denotes the logging options for a particular firewall rule. If logging is enabled, * logs will be exported to Cloud Logging. * @param logConfig logConfig or {@code null} for none */ public Firewall setLogConfig(FirewallLogConfig logConfig) { this.logConfig = logConfig; return this; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Name of the resource; provided by the client when the resource is created. The name must be * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?. The first character must be * a lowercase letter, and all following characters (except for the last character) must be a * dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. * @param name name or {@code null} for none */ public Firewall setName(java.lang.String name) { this.name = name; return this; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * @return value or {@code null} for none */ public java.lang.String getNetwork() { return network; } /** * URL of the network resource for this firewall rule. If not specified when creating a firewall * rule, the default network is used: global/networks/default If you choose to specify this field, * you can specify the network as a full or partial URL. For example, the following are all valid * URLs: - https://www.googleapis.com/compute/v1/projects/myproject/global/networks/my-network * - projects/myproject/global/networks/my-network - global/networks/default * @param network network or {@code null} for none */ public Firewall setNetwork(java.lang.String network) { this.network = network; return this; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @return value or {@code null} for none */ public java.lang.Integer getPriority() { return priority; } /** * Priority for this rule. This is an integer between `0` and `65535`, both inclusive. The default * value is `1000`. Relative priorities determine which rule takes effect if multiple rules apply. * Lower values indicate higher priority. For example, a rule with priority `0` has higher * precedence than a rule with priority `1`. DENY rules take precedence over ALLOW rules if they * have equal priority. Note that VPC networks have implied rules with a priority of `65535`. To * avoid conflicts with the implied rules, use a priority number less than `65535`. * @param priority priority or {@code null} for none */ public Firewall setPriority(java.lang.Integer priority) { this.priority = priority; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Firewall setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @return value or {@code null} for none */ public java.lang.String getSelfLinkWithId() { return selfLinkWithId; } /** * [Output Only] Server-defined URL for this resource with the resource id. * @param selfLinkWithId selfLinkWithId or {@code null} for none */ public Firewall setSelfLinkWithId(java.lang.String selfLinkWithId) { this.selfLinkWithId = selfLinkWithId; return this; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceRanges() { return sourceRanges; } /** * If source ranges are specified, the firewall rule applies only to traffic that has a source IP * address in these ranges. These ranges must be expressed in CIDR format. One or both of * sourceRanges and sourceTags may be set. If both fields are set, the rule applies to traffic * that has a source IP address within sourceRanges OR a source IP from a resource with a matching * tag listed in the sourceTags field. The connection does not need to match both fields for the * rule to apply. Only IPv4 is supported. * @param sourceRanges sourceRanges or {@code null} for none */ public Firewall setSourceRanges(java.util.List<java.lang.String> sourceRanges) { this.sourceRanges = sourceRanges; return this; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceServiceAccounts() { return sourceServiceAccounts; } /** * If source service accounts are specified, the firewall rules apply only to traffic originating * from an instance with a service account in this list. Source service accounts cannot be used to * control traffic to an instance's external IP address because service accounts are associated * with an instance, not an IP address. sourceRanges can be set at the same time as * sourceServiceAccounts. If both are set, the firewall applies to traffic that has a source IP * address within the sourceRanges OR a source IP that belongs to an instance with service account * listed in sourceServiceAccount. The connection does not need to match both fields for the * firewall to apply. sourceServiceAccounts cannot be used at the same time as sourceTags or * targetTags. * @param sourceServiceAccounts sourceServiceAccounts or {@code null} for none */ public Firewall setSourceServiceAccounts(java.util.List<java.lang.String> sourceServiceAccounts) { this.sourceServiceAccounts = sourceServiceAccounts; return this; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSourceTags() { return sourceTags; } /** * If source tags are specified, the firewall rule applies only to traffic with source IPs that * match the primary network interfaces of VM instances that have the tag and are in the same VPC * network. Source tags cannot be used to control traffic to an instance's external IP address, it * only applies to traffic between instances in the same virtual network. Because tags are * associated with instances, not IP addresses. One or both of sourceRanges and sourceTags may be * set. If both fields are set, the firewall applies to traffic that has a source IP address * within sourceRanges OR a source IP from a resource with a matching tag listed in the sourceTags * field. The connection does not need to match both fields for the firewall to apply. * @param sourceTags sourceTags or {@code null} for none */ public Firewall setSourceTags(java.util.List<java.lang.String> sourceTags) { this.sourceTags = sourceTags; return this; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetServiceAccounts() { return targetServiceAccounts; } /** * A list of service accounts indicating sets of instances located in the network that may make * network connections as specified in allowed[]. targetServiceAccounts cannot be used at the same * time as targetTags or sourceTags. If neither targetServiceAccounts nor targetTags are * specified, the firewall rule applies to all instances on the specified network. * @param targetServiceAccounts targetServiceAccounts or {@code null} for none */ public Firewall setTargetServiceAccounts(java.util.List<java.lang.String> targetServiceAccounts) { this.targetServiceAccounts = targetServiceAccounts; return this; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTargetTags() { return targetTags; } /** * A list of tags that controls which instances the firewall rule applies to. If targetTags are * specified, then the firewall rule applies only to instances in the VPC network that have one of * those tags. If no targetTags are specified, the firewall rule applies to all instances on the * specified network. * @param targetTags targetTags or {@code null} for none */ public Firewall setTargetTags(java.util.List<java.lang.String> targetTags) { this.targetTags = targetTags; return this; } @Override public Firewall set(String fieldName, Object value) { return (Firewall) super.set(fieldName, value); } @Override public Firewall clone() { return (Firewall) super.clone(); } /** * Model definition for FirewallAllowed. */ public static final class Allowed extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Allowed setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @param ports ports or {@code null} for none */ public Allowed setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Allowed set(String fieldName, Object value) { return (Allowed) super.set(fieldName, value); } @Override public Allowed clone() { return (Allowed) super.clone(); } } /** * Model definition for FirewallDenied. */ public static final class Denied extends com.google.api.client.json.GenericJson { /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * The value may be {@code null}. */ @com.google.api.client.util.Key("IPProtocol") private java.lang.String iPProtocol; /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> ports; /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @return value or {@code null} for none */ public java.lang.String getIPProtocol() { return iPProtocol; } /** * The IP protocol to which this rule applies. The protocol type is required when creating a * firewall rule. This value can either be one of the following well known protocol strings (tcp, * udp, icmp, esp, ah, ipip, sctp) or the IP protocol number. * @param iPProtocol iPProtocol or {@code null} for none */ public Denied setIPProtocol(java.lang.String iPProtocol) { this.iPProtocol = iPProtocol; return this; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPorts() { return ports; } /** * An optional list of ports to which this rule applies. This field is only applicable for the UDP * or TCP protocol. Each entry must be either an integer or a range. If not specified, this rule * applies to connections through any port. * * Example inputs include: ["22"], ["80","443"], and ["12345-12349"]. * @param ports ports or {@code null} for none */ public Denied setPorts(java.util.List<java.lang.String> ports) { this.ports = ports; return this; } @Override public Denied set(String fieldName, Object value) { return (Denied) super.set(fieldName, value); } @Override public Denied clone() { return (Denied) super.clone(); } } }
oracle/graalpython
36,513
graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/zlib/ZLibModuleBuiltins.java
/* * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.graal.python.builtins.modules.zlib; import static com.oracle.graal.python.builtins.PythonBuiltinClassType.ValueError; import static com.oracle.graal.python.builtins.modules.zlib.ZlibNodes.Z_OK; import static com.oracle.graal.python.nodes.ErrorMessages.EXPECTED_BYTESLIKE_GOT_P; import static com.oracle.graal.python.runtime.exception.PythonErrorType.TypeError; import static com.oracle.graal.python.runtime.exception.PythonErrorType.ZLibError; import static com.oracle.graal.python.util.PythonUtils.TS_ENCODING; import static com.oracle.graal.python.util.PythonUtils.crc32; import static com.oracle.graal.python.util.PythonUtils.tsLiteral; import static java.util.zip.Deflater.DEFAULT_COMPRESSION; import java.util.List; import java.util.zip.Adler32; import java.util.zip.CRC32; import com.oracle.graal.python.PythonLanguage; import com.oracle.graal.python.annotations.ArgumentClinic; import com.oracle.graal.python.annotations.ClinicConverterFactory; import com.oracle.graal.python.annotations.ClinicConverterFactory.UseDefaultForNone; import com.oracle.graal.python.annotations.Builtin; import com.oracle.graal.python.builtins.CoreFunctions; import com.oracle.graal.python.builtins.Python3Core; import com.oracle.graal.python.builtins.PythonBuiltins; import com.oracle.graal.python.builtins.modules.MathGuards; import com.oracle.graal.python.builtins.objects.PNone; import com.oracle.graal.python.builtins.objects.buffer.PythonBufferAccessLibrary; import com.oracle.graal.python.builtins.objects.bytes.BytesNodes; import com.oracle.graal.python.builtins.objects.bytes.BytesNodes.ToBytesNode; import com.oracle.graal.python.builtins.objects.bytes.PBytes; import com.oracle.graal.python.builtins.objects.bytes.PBytesLike; import com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes; import com.oracle.graal.python.builtins.objects.ints.PInt; import com.oracle.graal.python.builtins.objects.memoryview.PMemoryView; import com.oracle.graal.python.builtins.objects.module.PythonModule; import com.oracle.graal.python.lib.PyLongAsIntNode; import com.oracle.graal.python.nodes.ErrorMessages; import com.oracle.graal.python.nodes.PRaiseNode; import com.oracle.graal.python.nodes.function.PythonBuiltinBaseNode; import com.oracle.graal.python.nodes.function.builtins.PythonBinaryClinicBuiltinNode; import com.oracle.graal.python.nodes.function.builtins.PythonClinicBuiltinNode; import com.oracle.graal.python.nodes.function.builtins.PythonTernaryClinicBuiltinNode; import com.oracle.graal.python.nodes.function.builtins.clinic.ArgumentCastNode; import com.oracle.graal.python.nodes.function.builtins.clinic.ArgumentClinicProvider; import com.oracle.graal.python.runtime.IndirectCallData; import com.oracle.graal.python.runtime.NFIZlibSupport; import com.oracle.graal.python.runtime.NativeLibrary; import com.oracle.graal.python.runtime.PythonContext; import com.oracle.graal.python.runtime.object.PFactory; import com.oracle.graal.python.util.PythonUtils; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.Bind; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Cached.Shared; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.GenerateCached; import com.oracle.truffle.api.dsl.GenerateInline; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.ImportStatic; import com.oracle.truffle.api.dsl.NeverDefault; import com.oracle.truffle.api.dsl.NodeFactory; import com.oracle.truffle.api.dsl.NonIdempotent; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.UnsupportedMessageException; import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.strings.TruffleString; @CoreFunctions(defineModule = ZLibModuleBuiltins.J_ZLIB) public final class ZLibModuleBuiltins extends PythonBuiltins { protected static final String J_ZLIB = "zlib"; protected static final TruffleString T_ZLIB = tsLiteral(J_ZLIB); /* * There isn't currently a dynamic way to ask the jdk about the zlib version. so, we got it * manually from: "jdk/blob/master/src/java.base/share/native/libzip/zlib/README". The last time * zlib been updated in the JDK was on Sep 12, 2017. */ private static final TruffleString T_JDK_ZLIB_VERSION = tsLiteral("1.2.11"); // copied from zlib/blob/master/zlib.h /*- Allowed flush values; see deflate() and inflate() below for details */ public static final int Z_NO_FLUSH = 0; public static final int Z_PARTIAL_FLUSH = 1; // JDK doesn't support it. public static final int Z_SYNC_FLUSH = 2; public static final int Z_FULL_FLUSH = 3; public static final int Z_FINISH = 4; public static final int Z_BLOCK = 5; // JDK doesn't support it. public static final int Z_TREES = 6; // JDK doesn't support it. /*- compression levels */ public static final int Z_NO_COMPRESSION = 0; public static final int Z_BEST_SPEED = 1; public static final int Z_BEST_COMPRESSION = 9; public static final int Z_DEFAULT_COMPRESSION = -1; /*- compression strategy; see deflateInit2() below for details */ public static final int Z_FILTERED = 1; public static final int Z_HUFFMAN_ONLY = 2; public static final int Z_RLE = 3; public static final int Z_FIXED = 4; public static final int Z_DEFAULT_STRATEGY = 0; /*- The deflate compression method (the only one supported in this version) */ public static final int DEFLATED = 8; protected static final int MAX_WBITS = 15; protected static final int DEF_MEM_LEVEL = 8; protected static final int DEF_BUF_SIZE = 16 * 1024; @Override protected List<? extends NodeFactory<? extends PythonBuiltinBaseNode>> getNodeFactories() { return ZLibModuleBuiltinsFactory.getFactories(); } @Override public void initialize(Python3Core core) { super.initialize(core); addBuiltinConstant("Z_NO_COMPRESSION", Z_NO_COMPRESSION); addBuiltinConstant("Z_BEST_SPEED", Z_BEST_SPEED); addBuiltinConstant("Z_BEST_COMPRESSION", Z_BEST_COMPRESSION); addBuiltinConstant("Z_DEFAULT_COMPRESSION", Z_DEFAULT_COMPRESSION); addBuiltinConstant("Z_FILTERED", Z_FILTERED); addBuiltinConstant("Z_HUFFMAN_ONLY", Z_HUFFMAN_ONLY); addBuiltinConstant("Z_RLE", Z_RLE); addBuiltinConstant("Z_FIXED", Z_FIXED); addBuiltinConstant("Z_DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY); addBuiltinConstant("Z_NO_FLUSH", Z_NO_FLUSH); addBuiltinConstant("Z_SYNC_FLUSH", Z_SYNC_FLUSH); addBuiltinConstant("Z_FULL_FLUSH", Z_FULL_FLUSH); addBuiltinConstant("Z_FINISH", Z_FINISH); addBuiltinConstant("DEFLATED", DEFLATED); addBuiltinConstant("MAX_WBITS", MAX_WBITS); addBuiltinConstant("DEF_MEM_LEVEL", DEF_MEM_LEVEL); addBuiltinConstant("DEF_BUF_SIZE", DEF_BUF_SIZE); } @Override public void postInitialize(Python3Core core) { super.postInitialize(core); NFIZlibSupport zlibSupport = core.getContext().getNFIZlibSupport(); PythonModule zlibModule = core.lookupBuiltinModule(T_ZLIB); // isAvailable() checked already if native access is allowed TruffleString ver = T_JDK_ZLIB_VERSION; TruffleString rtver = T_JDK_ZLIB_VERSION; if (zlibSupport.isAvailable()) { try { ver = asString(zlibSupport.zlibVersion()); rtver = asString(zlibSupport.zlibRuntimeVersion()); zlibModule.setAttribute(tsLiteral("Z_PARTIAL_FLUSH"), Z_PARTIAL_FLUSH); zlibModule.setAttribute(tsLiteral("Z_BLOCK"), Z_BLOCK); zlibModule.setAttribute(tsLiteral("Z_TREES"), Z_TREES); } catch (NativeLibrary.NativeLibraryCannotBeLoaded e) { zlibSupport.notAvailable(); // ignore and proceed without native zlib support and use jdk's. } } zlibModule.setAttribute(tsLiteral("ZLIB_VERSION"), ver); zlibModule.setAttribute(tsLiteral("ZLIB_RUNTIME_VERSION"), rtver); } private static TruffleString asString(Object o) { if (o != null) { try { return InteropLibrary.getUncached().asTruffleString(o).switchEncodingUncached(TS_ENCODING); } catch (UnsupportedMessageException e) { // pass through } } return null; } @ImportStatic(MathGuards.class) public abstract static class ExpectIntNode extends ArgumentCastNode { private final Object defaultValue; protected ExpectIntNode(Object defaultValue) { this.defaultValue = defaultValue; } @Override public abstract Object execute(VirtualFrame frame, Object value); @Specialization Object none(@SuppressWarnings("unused") PNone none) { return defaultValue; } @Specialization static int doInt(int i) { // fast-path for the most common case return i; } @Specialization static int doBool(boolean b) { return PInt.intValue(b); } @Specialization public int toInt(long x) { // lost magnitude is ok here. return (int) x; } @Specialization public int toInt(PInt x) { // lost magnitude is ok here. return x.intValue(); } @Specialization(guards = {"!isPNone(value)", "!isInteger(value)"}) static Object doOthers(VirtualFrame frame, Object value, @Bind Node inliningTarget, @Cached PyLongAsIntNode asIntNode) { return asIntNode.execute(frame, inliningTarget, value); } protected ExpectIntNode createRec() { return ZLibModuleBuiltinsFactory.ExpectIntNodeGen.create(defaultValue); } @ClinicConverterFactory @NeverDefault public static ExpectIntNode create(@ClinicConverterFactory.DefaultValue Object defaultValue, @UseDefaultForNone boolean useDefaultForNone) { assert useDefaultForNone; // the other way around is not supported yet by this convertor return ZLibModuleBuiltinsFactory.ExpectIntNodeGen.create(defaultValue); } } public abstract static class ExpectByteLikeNode extends ArgumentCastNode { private final byte[] defaultValue; protected ExpectByteLikeNode(byte[] defaultValue) { this.defaultValue = defaultValue; } @Override public abstract Object execute(VirtualFrame frame, Object value); @Specialization byte[] handleNone(@SuppressWarnings("unused") PNone none) { return defaultValue; } @Specialization static byte[] doBytes(PBytesLike bytesLike, @Shared("b") @Cached BytesNodes.ToBytesNode toBytesNode) { return toBytesNode.execute(bytesLike); } @Specialization static byte[] doMemView(VirtualFrame frame, PMemoryView bytesLike, @Shared("b") @Cached BytesNodes.ToBytesNode toBytesNode) { return toBytesNode.execute(frame, bytesLike); } @Fallback static byte[] error(@SuppressWarnings("unused") VirtualFrame frame, Object value, @Bind Node inliningTarget) { throw PRaiseNode.raiseStatic(inliningTarget, TypeError, ErrorMessages.BYTESLIKE_OBJ_REQUIRED, value); } @ClinicConverterFactory @NeverDefault public static ExpectByteLikeNode create(@ClinicConverterFactory.DefaultValue byte[] defaultValue, @UseDefaultForNone boolean useDefaultForNone) { assert useDefaultForNone; // the other way around is not supported yet by this convertor return ZLibModuleBuiltinsFactory.ExpectByteLikeNodeGen.create(defaultValue); } } // zlib.crc32(data[, value]) @Builtin(name = "crc32", minNumOfPositionalArgs = 1, parameterNames = {"data", "value"}) @ArgumentClinic(name = "value", conversionClass = ZLibModuleBuiltins.ExpectIntNode.class, defaultValue = "PNone.NO_VALUE", useDefaultForNone = true) @GenerateNodeFactory public abstract static class Crc32Node extends PythonBinaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ZLibModuleBuiltinsClinicProviders.Crc32NodeClinicProviderGen.INSTANCE; } @NonIdempotent protected boolean useNative() { return PythonContext.get(this).getNFIZlibSupport().isAvailable(); } @Specialization long doitNone(VirtualFrame frame, Object data, @SuppressWarnings("unused") PNone value, @Shared("bb") @Cached ToBytesNode toBytesNode) { return doCRC32(toBytesNode.execute(frame, data)); } @TruffleBoundary static long doCRC32(byte[] data) { CRC32 crc32 = new CRC32(); crc32.update(data); return crc32.getValue(); } @Specialization(guards = "useNative()") long doNativeBytes(PBytesLike data, int value, @Bind Node inliningTarget, @Shared("b") @Cached SequenceStorageNodes.GetInternalBytesNode toBytes, @Shared @Cached NativeLibrary.InvokeNativeFunction invoke) { byte[] bytes = toBytes.execute(inliningTarget, data); int len = data.getSequenceStorage().length(); return nativeCrc32(bytes, len, value, invoke); } @Specialization(guards = {"useNative()", "!isBytes(data)"}) long doNativeObject(VirtualFrame frame, Object data, int value, @Shared("bb") @Cached ToBytesNode toBytesNode, @Shared @Cached NativeLibrary.InvokeNativeFunction invoke) { byte[] bytes = toBytesNode.execute(frame, data); return nativeCrc32(bytes, bytes.length, value, invoke); } @Specialization(guards = "!useNative()") static long doJavaBytes(PBytesLike data, int value, @Bind Node inliningTarget, @Shared("b") @Cached SequenceStorageNodes.GetInternalBytesNode toBytes) { byte[] bytes = toBytes.execute(inliningTarget, data); int len = data.getSequenceStorage().length(); return crc32(value, bytes, 0, len); } @Specialization(guards = {"!useNative()", "!isBytes(data)"}) static long doJavaObject(VirtualFrame frame, Object data, int value, @Shared("bb") @Cached ToBytesNode toBytesNode) { byte[] bytes = toBytesNode.execute(frame, data); return crc32(value, bytes, 0, bytes.length); } @Fallback static long error(Object data, @SuppressWarnings("unused") Object value, @Bind Node inliningTarget) { throw PRaiseNode.raiseStatic(inliningTarget, TypeError, EXPECTED_BYTESLIKE_GOT_P, data); } long nativeCrc32(byte[] bytes, int len, int value, NativeLibrary.InvokeNativeFunction invoke) { PythonContext ctxt = getContext(); int signedVal = (int) ctxt.getNFIZlibSupport().crc32(value, bytes, len, invoke); return signedVal & 0xFFFFFFFFL; } } // zlib.adler32(data[, value]) @Builtin(name = "adler32", minNumOfPositionalArgs = 1, numOfPositionalOnlyArgs = 2, parameterNames = {"data", "value"}) @ArgumentClinic(name = "value", conversionClass = ZLibModuleBuiltins.ExpectIntNode.class, defaultValue = "PNone.NO_VALUE", useDefaultForNone = true) @GenerateNodeFactory public abstract static class Adler32Node extends PythonBinaryClinicBuiltinNode { private static final int DEFER = 3850; private static final int BASE = 65521; @Override protected ArgumentClinicProvider getArgumentClinic() { return ZLibModuleBuiltinsClinicProviders.Adler32NodeClinicProviderGen.INSTANCE; } @NonIdempotent protected boolean useNative() { return getContext().getNFIZlibSupport().isAvailable(); } @Specialization long doitNone(VirtualFrame frame, Object data, @SuppressWarnings("unused") PNone value, @Shared("bb") @Cached ToBytesNode toBytesNode) { return doAdler32(toBytesNode.execute(frame, data)); } @TruffleBoundary private static long doAdler32(byte[] bytes) { Adler32 adler32 = new Adler32(); adler32.update(bytes); return adler32.getValue(); } @Specialization(guards = "useNative()") long doNativeBytes(PBytesLike data, int value, @Bind Node inliningTarget, @Shared("b") @Cached SequenceStorageNodes.GetInternalBytesNode toBytes, @Shared @Cached NativeLibrary.InvokeNativeFunction invoke) { byte[] bytes = toBytes.execute(inliningTarget, data); int len = data.getSequenceStorage().length(); return nativeAdler32(bytes, len, value, PythonContext.get(this), invoke); } @Specialization(guards = {"useNative()", "!isBytes(data)"}) long doNativeObject(VirtualFrame frame, Object data, int value, @Shared("bb") @Cached ToBytesNode toBytesNode, @Shared @Cached NativeLibrary.InvokeNativeFunction invoke) { byte[] bytes = toBytesNode.execute(frame, data); return nativeAdler32(bytes, bytes.length, value, PythonContext.get(this), invoke); } @Specialization(guards = "!useNative()") long doJavaBytes(PBytesLike data, int value, @Bind Node inliningTarget, @Shared("b") @Cached SequenceStorageNodes.GetInternalBytesNode toBytes) { byte[] bytes = toBytes.execute(inliningTarget, data); int len = data.getSequenceStorage().length(); return javaAdler32(bytes, len, value); } @Specialization(guards = {"!useNative()", "!isBytes(data)"}) long doJavaObject(VirtualFrame frame, Object data, int value, @Shared("bb") @Cached ToBytesNode toBytesNode) { byte[] bytes = toBytesNode.execute(frame, data); return javaAdler32(bytes, bytes.length, value); } long nativeAdler32(byte[] bytes, int len, int value, PythonContext ctxt, NativeLibrary.InvokeNativeFunction invoke) { int signedVal = (int) ctxt.getNFIZlibSupport().adler32(value, bytes, len, invoke); return signedVal & 0xFFFFFFFFL; } long javaAdler32(byte[] bytes, int len, int value) { int index = 0; int result = value; int s1 = result & 0xffff; int s2 = result >>> 16; while (index < len) { int max = Math.min(index + DEFER, index + len); while (index < max) { s1 = (bytes[index++] & 0xff) + s1; s2 += s1; } s1 %= BASE; s2 %= BASE; } result = (s2 << 16) | s1; return result & 0xFFFFFFFFL; } } // zlib.compress(data, level=-1) @Builtin(name = "compress", minNumOfPositionalArgs = 1, numOfPositionalOnlyArgs = 1, parameterNames = {"data", "level", "wbits"}) @ArgumentClinic(name = "data", conversion = ArgumentClinic.ClinicConversion.ReadableBuffer) @ArgumentClinic(name = "level", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.Z_DEFAULT_COMPRESSION", useDefaultForNone = true) @ArgumentClinic(name = "wbits", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.MAX_WBITS", useDefaultForNone = true) @GenerateNodeFactory public abstract static class CompressNode extends PythonTernaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ZLibModuleBuiltinsClinicProviders.CompressNodeClinicProviderGen.INSTANCE; } @Specialization static PBytes compress(VirtualFrame frame, Object buffer, int level, int wbits, @Bind Node inliningTarget, @Bind PythonLanguage language, @CachedLibrary(limit = "3") PythonBufferAccessLibrary bufferLib, @Cached("createFor($node)") IndirectCallData indirectCallData, @Cached CompressInnerNode innerNode) { try { byte[] bytes = bufferLib.getInternalOrCopiedByteArray(buffer); int len = bufferLib.getBufferLength(buffer); byte[] resultArray = innerNode.execute(inliningTarget, bytes, len, level, wbits); return PFactory.createBytes(language, resultArray); } finally { bufferLib.release(buffer, frame, indirectCallData); } } @GenerateInline @GenerateCached(false) abstract static class CompressInnerNode extends Node { abstract byte[] execute(Node inliningTarget, byte[] bytes, int length, int level, int wbits); @NonIdempotent protected boolean useNative() { return PythonContext.get(this).getNFIZlibSupport().isAvailable(); } protected static boolean isValidLevel(int level) { return !((level < 0 || level > 9) && level != DEFAULT_COMPRESSION); } @Specialization(guards = "useNative()") static byte[] doNative(Node inliningTarget, byte[] bytes, int length, int level, int wbits, @Cached ZlibNodes.ZlibNativeCompress nativeCompress) { return nativeCompress.execute(inliningTarget, bytes, length, level, wbits); } @Specialization(guards = {"!useNative()", "isValidLevel(level)"}) static byte[] doJava(byte[] bytes, int length, int level, int wbits, @Bind Node inliningTarget) { return JavaCompress.compressFinish(bytes, length, level, wbits, inliningTarget); } @Specialization(guards = {"!useNative()", "!isValidLevel(level)"}) static byte[] doJavaLevelError(byte[] bytes, int length, int level, int wbits, @Bind Node inliningTarget) { throw PRaiseNode.raiseStatic(inliningTarget, ZLibError, ErrorMessages.BAD_COMPRESSION_LEVEL); } } } // zlib.decompress(data, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE) @Builtin(name = "decompress", minNumOfPositionalArgs = 1, numOfPositionalOnlyArgs = 1, parameterNames = {"data", "wbits", "bufsize"}) @ArgumentClinic(name = "data", conversion = ArgumentClinic.ClinicConversion.ReadableBuffer) @ArgumentClinic(name = "wbits", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.MAX_WBITS", useDefaultForNone = true) @ArgumentClinic(name = "bufsize", conversion = ArgumentClinic.ClinicConversion.Index, defaultValue = "ZLibModuleBuiltins.DEF_BUF_SIZE", useDefaultForNone = true) @GenerateNodeFactory public abstract static class DecompressNode extends PythonTernaryClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ZLibModuleBuiltinsClinicProviders.DecompressNodeClinicProviderGen.INSTANCE; } @Specialization static PBytes decompress(VirtualFrame frame, Object buffer, int wbits, int bufsize, @Bind Node inliningTarget, @Bind PythonLanguage language, @CachedLibrary(limit = "3") PythonBufferAccessLibrary bufferLib, @Cached("createFor($node)") IndirectCallData indirectCallData, @Cached DecompressInnerNode innerNode, @Cached PRaiseNode raiseNode) { try { if (bufsize < 0) { throw raiseNode.raise(inliningTarget, ZLibError, ErrorMessages.MUST_BE_NON_NEGATIVE, "bufsize"); } byte[] bytes = bufferLib.getInternalOrCopiedByteArray(buffer); int len = bufferLib.getBufferLength(buffer); byte[] resultArray = innerNode.execute(inliningTarget, bytes, len, wbits, bufsize); return PFactory.createBytes(language, resultArray); } finally { bufferLib.release(buffer, frame, indirectCallData); } } @GenerateInline @GenerateCached(false) abstract static class DecompressInnerNode extends Node { abstract byte[] execute(Node inliningTarget, byte[] bytes, int length, int wbits, int bufsize); @NonIdempotent protected boolean useNative() { return PythonContext.get(this).getNFIZlibSupport().isAvailable(); } @Specialization(guards = "useNative()") static byte[] doNative(Node inliningTarget, byte[] bytes, int length, int wbits, int bufsize, @Cached ZlibNodes.ZlibNativeDecompress nativeDecompress) { return nativeDecompress.execute(inliningTarget, bytes, length, wbits, bufsize, PythonContext.get(inliningTarget)); } @Specialization(guards = "!useNative()") @TruffleBoundary static byte[] doJava(Node inliningTarget, byte[] bytes, int length, int wbits, int bufsize) { return JavaDecompress.decompress(bytes, length, wbits, bufsize == 0 ? 1 : bufsize, inliningTarget); } } } protected static final byte[] EMPTY_BYTE_ARRAY = PythonUtils.EMPTY_BYTE_ARRAY; @ImportStatic(ZLibModuleBuiltins.class) @Builtin(name = "compressobj", parameterNames = {"level", "method", "wbits", "memLevel", "strategy", "zdict"}) @ArgumentClinic(name = "level", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "-1", useDefaultForNone = true) @ArgumentClinic(name = "method", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.DEFLATED", useDefaultForNone = true) @ArgumentClinic(name = "wbits", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.MAX_WBITS", useDefaultForNone = true) @ArgumentClinic(name = "memLevel", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.DEF_MEM_LEVEL", useDefaultForNone = true) @ArgumentClinic(name = "strategy", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.Z_DEFAULT_STRATEGY", useDefaultForNone = true) @ArgumentClinic(name = "zdict", conversionClass = ExpectByteLikeNode.class, defaultValue = "ZLibModuleBuiltins.EMPTY_BYTE_ARRAY", useDefaultForNone = true) @GenerateNodeFactory abstract static class CompressObjNode extends PythonClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ZLibModuleBuiltinsClinicProviders.CompressObjNodeClinicProviderGen.INSTANCE; } @NonIdempotent protected boolean useNative() { return PythonContext.get(this).getNFIZlibSupport().isAvailable(); } protected static boolean isValidWBitRange(int wbits) { return wbits < -7 || (wbits > 7 && wbits <= MAX_WBITS) || (wbits > (MAX_WBITS + 9) && wbits <= (MAX_WBITS + 16)); } @Specialization(guards = {"method == DEFLATED", "useNative()"}) static Object doNative(int level, int method, int wbits, int memLevel, int strategy, byte[] zdict, @Bind Node inliningTarget, @Bind PythonLanguage language, @Cached NativeLibrary.InvokeNativeFunction createCompObject, @Cached NativeLibrary.InvokeNativeFunction compressObjInit, @Cached ZlibNodes.ZlibNativeErrorHandling errorHandling) { NFIZlibSupport zlibSupport = PythonContext.get(inliningTarget).getNFIZlibSupport(); Object zst = zlibSupport.createCompObject(createCompObject); int err; if (zdict.length > 0) { err = zlibSupport.compressObjInitWithDict(zst, level, method, wbits, memLevel, strategy, zdict, zdict.length, compressObjInit); } else { err = zlibSupport.compressObjInit(zst, level, method, wbits, memLevel, strategy, compressObjInit); } if (err != Z_OK) { errorHandling.execute(inliningTarget, zst, err, zlibSupport, true); } return PFactory.createNativeZLibCompObjectCompress(language, zst, zlibSupport); } /** * @param memLevel is ignored - it mostly affects performance and compression rate, we trust * that the Deflater implementation will work well */ @TruffleBoundary @Specialization(guards = {"method == DEFLATED", "!useNative()", "isValidWBitRange(wbits)"}) static Object doJava(int level, @SuppressWarnings("unused") int method, int wbits, @SuppressWarnings("unused") int memLevel, int strategy, byte[] zdict, @Bind PythonLanguage language) { JavaCompress compress = PFactory.createJavaZLibCompObjectCompress(language, level, wbits, strategy, zdict); compress.setStrategy(); compress.setDictionary(); return compress; } @SuppressWarnings("unused") @Specialization(guards = {"method == DEFLATED", "!useNative()", "!isValidWBitRange(wbits)"}) static Object invalid(int level, int method, int wbits, int memLevel, int strategy, byte[] zdict, @Bind Node inliningTarget) { throw PRaiseNode.raiseStatic(inliningTarget, ValueError, ErrorMessages.INVALID_INITIALIZATION_OPTION); } @SuppressWarnings("unused") @Specialization(guards = {"method != DEFLATED"}) static Object methodErr(int level, int method, int wbits, int memLevel, int strategy, byte[] zdict, @Bind Node inliningTarget) { throw PRaiseNode.raiseStatic(inliningTarget, ValueError, ErrorMessages.ONLY_DEFLATED_ALLOWED_AS_METHOD, DEFLATED, method); } } @Builtin(name = "decompressobj", parameterNames = {"wbits", "zdict"}) @ArgumentClinic(name = "wbits", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "ZLibModuleBuiltins.MAX_WBITS", useDefaultForNone = true) @ArgumentClinic(name = "zdict", conversionClass = ExpectByteLikeNode.class, defaultValue = "ZLibModuleBuiltins.EMPTY_BYTE_ARRAY", useDefaultForNone = true) @GenerateNodeFactory abstract static class DecompressObjNode extends PythonClinicBuiltinNode { @Override protected ArgumentClinicProvider getArgumentClinic() { return ZLibModuleBuiltinsClinicProviders.DecompressObjNodeClinicProviderGen.INSTANCE; } @NonIdempotent protected boolean useNative() { return PythonContext.get(this).getNFIZlibSupport().isAvailable(); } protected static boolean isValidWBitRange(int wbits) { return wbits < -7 || (wbits > 7 && wbits <= MAX_WBITS) || (wbits > (MAX_WBITS + 9) && wbits <= (MAX_WBITS + 16)); } @Specialization(guards = {"useNative()"}) static Object doNative(int wbits, byte[] zdict, @Bind Node inliningTarget, @Bind PythonContext context, @Cached NativeLibrary.InvokeNativeFunction createCompObject, @Cached NativeLibrary.InvokeNativeFunction decompressObjInit, @Cached ZlibNodes.ZlibNativeErrorHandling errorHandling) { NFIZlibSupport zlibSupport = context.getNFIZlibSupport(); Object zst = zlibSupport.createCompObject(createCompObject); int err; if (zdict.length > 0) { err = zlibSupport.decompressObjInitWithDict(zst, wbits, zdict, zdict.length, decompressObjInit); } else { err = zlibSupport.decompressObjInit(zst, wbits, decompressObjInit); } if (err != Z_OK) { errorHandling.execute(inliningTarget, zst, err, zlibSupport, true); } return PFactory.createNativeZLibCompObjectDecompress(context.getLanguage(inliningTarget), zst, zlibSupport); } @TruffleBoundary @Specialization(guards = {"!useNative()", "isValidWBitRange(wbits)"}) static Object doJava(int wbits, byte[] zdict) { // wbits < 0: generate a RAW stream, i.e., no wrapping // wbits 25..31: gzip container, i.e., no wrapping // Otherwise: wrap stream with zlib header and trailer boolean isRAW = wbits < 0; PythonLanguage language = PythonLanguage.get(null); JavaDecompress obj = PFactory.createJavaZLibCompObjectDecompress(language, wbits, zdict); if (isRAW) { obj.setDictionary(); } obj.setUnusedData(PFactory.createEmptyBytes(language)); obj.setUnconsumedTail(PFactory.createEmptyBytes(language)); return obj; } @SuppressWarnings("unused") @Specialization(guards = {"!useNative()", "!isValidWBitRange(wbits)"}) static Object invalid(int wbits, byte[] zdict, @Bind Node inliningTarget) { throw PRaiseNode.raiseStatic(inliningTarget, ValueError, ErrorMessages.INVALID_INITIALIZATION_OPTION); } } }
googleapis/google-cloud-java
36,354
java-analytics-admin/proto-google-analytics-admin-v1beta/src/main/java/com/google/analytics/admin/v1beta/ListAccountsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/analytics/admin/v1beta/analytics_admin.proto // Protobuf Java Version: 3.25.8 package com.google.analytics.admin.v1beta; /** * * * <pre> * Request message for ListAccounts RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.ListAccountsResponse} */ public final class ListAccountsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1beta.ListAccountsResponse) ListAccountsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListAccountsResponse.newBuilder() to construct. private ListAccountsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListAccountsResponse() { accounts_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListAccountsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListAccountsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListAccountsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.ListAccountsResponse.class, com.google.analytics.admin.v1beta.ListAccountsResponse.Builder.class); } public static final int ACCOUNTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.analytics.admin.v1beta.Account> accounts_; /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ @java.lang.Override public java.util.List<com.google.analytics.admin.v1beta.Account> getAccountsList() { return accounts_; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.analytics.admin.v1beta.AccountOrBuilder> getAccountsOrBuilderList() { return accounts_; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ @java.lang.Override public int getAccountsCount() { return accounts_.size(); } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1beta.Account getAccounts(int index) { return accounts_.get(index); } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1beta.AccountOrBuilder getAccountsOrBuilder(int index) { return accounts_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < accounts_.size(); i++) { output.writeMessage(1, accounts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < accounts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, accounts_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.analytics.admin.v1beta.ListAccountsResponse)) { return super.equals(obj); } com.google.analytics.admin.v1beta.ListAccountsResponse other = (com.google.analytics.admin.v1beta.ListAccountsResponse) obj; if (!getAccountsList().equals(other.getAccountsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getAccountsCount() > 0) { hash = (37 * hash) + ACCOUNTS_FIELD_NUMBER; hash = (53 * hash) + getAccountsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.ListAccountsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.analytics.admin.v1beta.ListAccountsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for ListAccounts RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.ListAccountsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1beta.ListAccountsResponse) com.google.analytics.admin.v1beta.ListAccountsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListAccountsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListAccountsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.ListAccountsResponse.class, com.google.analytics.admin.v1beta.ListAccountsResponse.Builder.class); } // Construct using com.google.analytics.admin.v1beta.ListAccountsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (accountsBuilder_ == null) { accounts_ = java.util.Collections.emptyList(); } else { accounts_ = null; accountsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_ListAccountsResponse_descriptor; } @java.lang.Override public com.google.analytics.admin.v1beta.ListAccountsResponse getDefaultInstanceForType() { return com.google.analytics.admin.v1beta.ListAccountsResponse.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1beta.ListAccountsResponse build() { com.google.analytics.admin.v1beta.ListAccountsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1beta.ListAccountsResponse buildPartial() { com.google.analytics.admin.v1beta.ListAccountsResponse result = new com.google.analytics.admin.v1beta.ListAccountsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.analytics.admin.v1beta.ListAccountsResponse result) { if (accountsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { accounts_ = java.util.Collections.unmodifiableList(accounts_); bitField0_ = (bitField0_ & ~0x00000001); } result.accounts_ = accounts_; } else { result.accounts_ = accountsBuilder_.build(); } } private void buildPartial0(com.google.analytics.admin.v1beta.ListAccountsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.analytics.admin.v1beta.ListAccountsResponse) { return mergeFrom((com.google.analytics.admin.v1beta.ListAccountsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1beta.ListAccountsResponse other) { if (other == com.google.analytics.admin.v1beta.ListAccountsResponse.getDefaultInstance()) return this; if (accountsBuilder_ == null) { if (!other.accounts_.isEmpty()) { if (accounts_.isEmpty()) { accounts_ = other.accounts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureAccountsIsMutable(); accounts_.addAll(other.accounts_); } onChanged(); } } else { if (!other.accounts_.isEmpty()) { if (accountsBuilder_.isEmpty()) { accountsBuilder_.dispose(); accountsBuilder_ = null; accounts_ = other.accounts_; bitField0_ = (bitField0_ & ~0x00000001); accountsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getAccountsFieldBuilder() : null; } else { accountsBuilder_.addAllMessages(other.accounts_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.analytics.admin.v1beta.Account m = input.readMessage( com.google.analytics.admin.v1beta.Account.parser(), extensionRegistry); if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(m); } else { accountsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.analytics.admin.v1beta.Account> accounts_ = java.util.Collections.emptyList(); private void ensureAccountsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { accounts_ = new java.util.ArrayList<com.google.analytics.admin.v1beta.Account>(accounts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1beta.Account, com.google.analytics.admin.v1beta.Account.Builder, com.google.analytics.admin.v1beta.AccountOrBuilder> accountsBuilder_; /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public java.util.List<com.google.analytics.admin.v1beta.Account> getAccountsList() { if (accountsBuilder_ == null) { return java.util.Collections.unmodifiableList(accounts_); } else { return accountsBuilder_.getMessageList(); } } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public int getAccountsCount() { if (accountsBuilder_ == null) { return accounts_.size(); } else { return accountsBuilder_.getCount(); } } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public com.google.analytics.admin.v1beta.Account getAccounts(int index) { if (accountsBuilder_ == null) { return accounts_.get(index); } else { return accountsBuilder_.getMessage(index); } } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder setAccounts(int index, com.google.analytics.admin.v1beta.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.set(index, value); onChanged(); } else { accountsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder setAccounts( int index, com.google.analytics.admin.v1beta.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.set(index, builderForValue.build()); onChanged(); } else { accountsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder addAccounts(com.google.analytics.admin.v1beta.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.add(value); onChanged(); } else { accountsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder addAccounts(int index, com.google.analytics.admin.v1beta.Account value) { if (accountsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAccountsIsMutable(); accounts_.add(index, value); onChanged(); } else { accountsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder addAccounts(com.google.analytics.admin.v1beta.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(builderForValue.build()); onChanged(); } else { accountsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder addAccounts( int index, com.google.analytics.admin.v1beta.Account.Builder builderForValue) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.add(index, builderForValue.build()); onChanged(); } else { accountsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder addAllAccounts( java.lang.Iterable<? extends com.google.analytics.admin.v1beta.Account> values) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, accounts_); onChanged(); } else { accountsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder clearAccounts() { if (accountsBuilder_ == null) { accounts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { accountsBuilder_.clear(); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public Builder removeAccounts(int index) { if (accountsBuilder_ == null) { ensureAccountsIsMutable(); accounts_.remove(index); onChanged(); } else { accountsBuilder_.remove(index); } return this; } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public com.google.analytics.admin.v1beta.Account.Builder getAccountsBuilder(int index) { return getAccountsFieldBuilder().getBuilder(index); } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public com.google.analytics.admin.v1beta.AccountOrBuilder getAccountsOrBuilder(int index) { if (accountsBuilder_ == null) { return accounts_.get(index); } else { return accountsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public java.util.List<? extends com.google.analytics.admin.v1beta.AccountOrBuilder> getAccountsOrBuilderList() { if (accountsBuilder_ != null) { return accountsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(accounts_); } } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public com.google.analytics.admin.v1beta.Account.Builder addAccountsBuilder() { return getAccountsFieldBuilder() .addBuilder(com.google.analytics.admin.v1beta.Account.getDefaultInstance()); } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public com.google.analytics.admin.v1beta.Account.Builder addAccountsBuilder(int index) { return getAccountsFieldBuilder() .addBuilder(index, com.google.analytics.admin.v1beta.Account.getDefaultInstance()); } /** * * * <pre> * Results that were accessible to the caller. * </pre> * * <code>repeated .google.analytics.admin.v1beta.Account accounts = 1;</code> */ public java.util.List<com.google.analytics.admin.v1beta.Account.Builder> getAccountsBuilderList() { return getAccountsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1beta.Account, com.google.analytics.admin.v1beta.Account.Builder, com.google.analytics.admin.v1beta.AccountOrBuilder> getAccountsFieldBuilder() { if (accountsBuilder_ == null) { accountsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1beta.Account, com.google.analytics.admin.v1beta.Account.Builder, com.google.analytics.admin.v1beta.AccountOrBuilder>( accounts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); accounts_ = null; } return accountsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.analytics.admin.v1beta.ListAccountsResponse) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1beta.ListAccountsResponse) private static final com.google.analytics.admin.v1beta.ListAccountsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1beta.ListAccountsResponse(); } public static com.google.analytics.admin.v1beta.ListAccountsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListAccountsResponse> PARSER = new com.google.protobuf.AbstractParser<ListAccountsResponse>() { @java.lang.Override public ListAccountsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListAccountsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListAccountsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1beta.ListAccountsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,598
java-apigee-registry/google-cloud-apigee-registry/src/main/java/com/google/cloud/apigeeregistry/v1/stub/HttpJsonProvisioningStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.apigeeregistry.v1.stub; import static com.google.cloud.apigeeregistry.v1.ProvisioningClient.ListLocationsPagedResponse; import com.google.api.HttpRule; import com.google.api.core.InternalApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.httpjson.ApiMethodDescriptor; import com.google.api.gax.httpjson.HttpJsonCallSettings; import com.google.api.gax.httpjson.HttpJsonOperationSnapshot; import com.google.api.gax.httpjson.HttpJsonStubCallableFactory; import com.google.api.gax.httpjson.ProtoMessageRequestFormatter; import com.google.api.gax.httpjson.ProtoMessageResponseParser; import com.google.api.gax.httpjson.ProtoRestSerializer; import com.google.api.gax.httpjson.longrunning.stub.HttpJsonOperationsStub; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.apigeeregistry.v1.CreateInstanceRequest; import com.google.cloud.apigeeregistry.v1.DeleteInstanceRequest; import com.google.cloud.apigeeregistry.v1.GetInstanceRequest; import com.google.cloud.apigeeregistry.v1.Instance; import com.google.cloud.apigeeregistry.v1.OperationMetadata; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.collect.ImmutableMap; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import com.google.longrunning.Operation; import com.google.protobuf.Empty; import com.google.protobuf.TypeRegistry; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * REST stub implementation for the Provisioning service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonProvisioningStub extends ProvisioningStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder() .add(Empty.getDescriptor()) .add(Instance.getDescriptor()) .add(OperationMetadata.getDescriptor()) .build(); private static final ApiMethodDescriptor<CreateInstanceRequest, Operation> createInstanceMethodDescriptor = ApiMethodDescriptor.<CreateInstanceRequest, Operation>newBuilder() .setFullMethodName("google.cloud.apigeeregistry.v1.Provisioning/CreateInstance") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<CreateInstanceRequest>newBuilder() .setPath( "/v1/{parent=projects/*/locations/*}/instances", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CreateInstanceRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CreateInstanceRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "instanceId", request.getInstanceId()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("instance", request.getInstance(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (CreateInstanceRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<DeleteInstanceRequest, Operation> deleteInstanceMethodDescriptor = ApiMethodDescriptor.<DeleteInstanceRequest, Operation>newBuilder() .setFullMethodName("google.cloud.apigeeregistry.v1.Provisioning/DeleteInstance") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeleteInstanceRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*/instances/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeleteInstanceRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeleteInstanceRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeleteInstanceRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<GetInstanceRequest, Instance> getInstanceMethodDescriptor = ApiMethodDescriptor.<GetInstanceRequest, Instance>newBuilder() .setFullMethodName("google.cloud.apigeeregistry.v1.Provisioning/GetInstance") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetInstanceRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*/instances/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetInstanceRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetInstanceRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Instance>newBuilder() .setDefaultInstance(Instance.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<ListLocationsRequest, ListLocationsResponse> listLocationsMethodDescriptor = ApiMethodDescriptor.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setFullMethodName("google.cloud.location.Locations/ListLocations") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListLocationsRequest>newBuilder() .setPath( "/v1/{name=projects/*}/locations", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListLocationsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListLocationsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListLocationsResponse>newBuilder() .setDefaultInstance(ListLocationsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetLocationRequest, Location> getLocationMethodDescriptor = ApiMethodDescriptor.<GetLocationRequest, Location>newBuilder() .setFullMethodName("google.cloud.location.Locations/GetLocation") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetLocationRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetLocationRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetLocationRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Location>newBuilder() .setDefaultInstance(Location.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor = ApiMethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder() .setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<SetIamPolicyRequest>newBuilder() .setPath( "/v1/{resource=projects/*/locations/*/apis/*}:setIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setAdditionalPaths( "/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/artifacts/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/instances/*}:setIamPolicy", "/v1/{resource=projects/*/locations/*/runtime}:setIamPolicy") .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<SetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearResource().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor = ApiMethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder() .setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetIamPolicyRequest>newBuilder() .setPath( "/v1/{resource=projects/*/locations/*/apis/*}:getIamPolicy", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setAdditionalPaths( "/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/artifacts/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/instances/*}:getIamPolicy", "/v1/{resource=projects/*/locations/*/runtime}:getIamPolicy") .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetIamPolicyRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Policy>newBuilder() .setDefaultInstance(Policy.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsMethodDescriptor = ApiMethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<TestIamPermissionsRequest>newBuilder() .setPath( "/v1/{resource=projects/*/locations/*/apis/*}:testIamPermissions", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "resource", request.getResource()); return fields; }) .setAdditionalPaths( "/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/apis/*/versions/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/artifacts/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/instances/*}:testIamPermissions", "/v1/{resource=projects/*/locations/*/runtime}:testIamPermissions") .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<TestIamPermissionsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearResource().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<TestIamPermissionsResponse>newBuilder() .setDefaultInstance(TestIamPermissionsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<CreateInstanceRequest, Operation> createInstanceCallable; private final OperationCallable<CreateInstanceRequest, Instance, OperationMetadata> createInstanceOperationCallable; private final UnaryCallable<DeleteInstanceRequest, Operation> deleteInstanceCallable; private final OperationCallable<DeleteInstanceRequest, Empty, OperationMetadata> deleteInstanceOperationCallable; private final UnaryCallable<GetInstanceRequest, Instance> getInstanceCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable; private final UnaryCallable<GetLocationRequest, Location> getLocationCallable; private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable; private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable; private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable; private final BackgroundResource backgroundResources; private final HttpJsonOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonProvisioningStub create(ProvisioningStubSettings settings) throws IOException { return new HttpJsonProvisioningStub(settings, ClientContext.create(settings)); } public static final HttpJsonProvisioningStub create(ClientContext clientContext) throws IOException { return new HttpJsonProvisioningStub( ProvisioningStubSettings.newHttpJsonBuilder().build(), clientContext); } public static final HttpJsonProvisioningStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonProvisioningStub( ProvisioningStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonProvisioningStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonProvisioningStub(ProvisioningStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonProvisioningCallableFactory()); } /** * Constructs an instance of HttpJsonProvisioningStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonProvisioningStub( ProvisioningStubSettings settings, ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.httpJsonOperationsStub = HttpJsonOperationsStub.create( clientContext, callableFactory, typeRegistry, ImmutableMap.<String, HttpRule>builder() .put( "google.longrunning.Operations.CancelOperation", HttpRule.newBuilder() .setPost("/v1/{name=projects/*/locations/*/operations/*}:cancel") .build()) .put( "google.longrunning.Operations.DeleteOperation", HttpRule.newBuilder() .setDelete("/v1/{name=projects/*/locations/*/operations/*}") .build()) .put( "google.longrunning.Operations.GetOperation", HttpRule.newBuilder() .setGet("/v1/{name=projects/*/locations/*/operations/*}") .build()) .put( "google.longrunning.Operations.ListOperations", HttpRule.newBuilder() .setGet("/v1/{name=projects/*/locations/*}/operations") .build()) .build()); HttpJsonCallSettings<CreateInstanceRequest, Operation> createInstanceTransportSettings = HttpJsonCallSettings.<CreateInstanceRequest, Operation>newBuilder() .setMethodDescriptor(createInstanceMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings<DeleteInstanceRequest, Operation> deleteInstanceTransportSettings = HttpJsonCallSettings.<DeleteInstanceRequest, Operation>newBuilder() .setMethodDescriptor(deleteInstanceMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<GetInstanceRequest, Instance> getInstanceTransportSettings = HttpJsonCallSettings.<GetInstanceRequest, Instance>newBuilder() .setMethodDescriptor(getInstanceMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<ListLocationsRequest, ListLocationsResponse> listLocationsTransportSettings = HttpJsonCallSettings.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setMethodDescriptor(listLocationsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<GetLocationRequest, Location> getLocationTransportSettings = HttpJsonCallSettings.<GetLocationRequest, Location>newBuilder() .setMethodDescriptor(getLocationMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings = HttpJsonCallSettings.<SetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(setIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings = HttpJsonCallSettings.<GetIamPolicyRequest, Policy>newBuilder() .setMethodDescriptor(getIamPolicyMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); HttpJsonCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsTransportSettings = HttpJsonCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder() .setMethodDescriptor(testIamPermissionsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("resource", String.valueOf(request.getResource())); return builder.build(); }) .build(); this.createInstanceCallable = callableFactory.createUnaryCallable( createInstanceTransportSettings, settings.createInstanceSettings(), clientContext); this.createInstanceOperationCallable = callableFactory.createOperationCallable( createInstanceTransportSettings, settings.createInstanceOperationSettings(), clientContext, httpJsonOperationsStub); this.deleteInstanceCallable = callableFactory.createUnaryCallable( deleteInstanceTransportSettings, settings.deleteInstanceSettings(), clientContext); this.deleteInstanceOperationCallable = callableFactory.createOperationCallable( deleteInstanceTransportSettings, settings.deleteInstanceOperationSettings(), clientContext, httpJsonOperationsStub); this.getInstanceCallable = callableFactory.createUnaryCallable( getInstanceTransportSettings, settings.getInstanceSettings(), clientContext); this.listLocationsCallable = callableFactory.createUnaryCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.listLocationsPagedCallable = callableFactory.createPagedCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.getLocationCallable = callableFactory.createUnaryCallable( getLocationTransportSettings, settings.getLocationSettings(), clientContext); this.setIamPolicyCallable = callableFactory.createUnaryCallable( setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext); this.getIamPolicyCallable = callableFactory.createUnaryCallable( getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext); this.testIamPermissionsCallable = callableFactory.createUnaryCallable( testIamPermissionsTransportSettings, settings.testIamPermissionsSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } @InternalApi public static List<ApiMethodDescriptor> getMethodDescriptors() { List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>(); methodDescriptors.add(createInstanceMethodDescriptor); methodDescriptors.add(deleteInstanceMethodDescriptor); methodDescriptors.add(getInstanceMethodDescriptor); methodDescriptors.add(listLocationsMethodDescriptor); methodDescriptors.add(getLocationMethodDescriptor); methodDescriptors.add(setIamPolicyMethodDescriptor); methodDescriptors.add(getIamPolicyMethodDescriptor); methodDescriptors.add(testIamPermissionsMethodDescriptor); return methodDescriptors; } public HttpJsonOperationsStub getHttpJsonOperationsStub() { return httpJsonOperationsStub; } @Override public UnaryCallable<CreateInstanceRequest, Operation> createInstanceCallable() { return createInstanceCallable; } @Override public OperationCallable<CreateInstanceRequest, Instance, OperationMetadata> createInstanceOperationCallable() { return createInstanceOperationCallable; } @Override public UnaryCallable<DeleteInstanceRequest, Operation> deleteInstanceCallable() { return deleteInstanceCallable; } @Override public OperationCallable<DeleteInstanceRequest, Empty, OperationMetadata> deleteInstanceOperationCallable() { return deleteInstanceOperationCallable; } @Override public UnaryCallable<GetInstanceRequest, Instance> getInstanceCallable() { return getInstanceCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return listLocationsCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return listLocationsPagedCallable; } @Override public UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return getLocationCallable; } @Override public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() { return setIamPolicyCallable; } @Override public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() { return getIamPolicyCallable; } @Override public UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable() { return testIamPermissionsCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
googleapis/google-cloud-java
36,432
java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/UpdateSecuritySettingsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/cx/v3/security_settings.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.cx.v3; /** * * * <pre> * The request message for * [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest} */ public final class UpdateSecuritySettingsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest) UpdateSecuritySettingsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateSecuritySettingsRequest.newBuilder() to construct. private UpdateSecuritySettingsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateSecuritySettingsRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateSecuritySettingsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3.SecuritySettingsProto .internal_static_google_cloud_dialogflow_cx_v3_UpdateSecuritySettingsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3.SecuritySettingsProto .internal_static_google_cloud_dialogflow_cx_v3_UpdateSecuritySettingsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest.class, com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest.Builder.class); } private int bitField0_; public static final int SECURITY_SETTINGS_FIELD_NUMBER = 1; private com.google.cloud.dialogflow.cx.v3.SecuritySettings securitySettings_; /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the securitySettings field is set. */ @java.lang.Override public boolean hasSecuritySettings() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The securitySettings. */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3.SecuritySettings getSecuritySettings() { return securitySettings_ == null ? com.google.cloud.dialogflow.cx.v3.SecuritySettings.getDefaultInstance() : securitySettings_; } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3.SecuritySettingsOrBuilder getSecuritySettingsOrBuilder() { return securitySettings_ == null ? com.google.cloud.dialogflow.cx.v3.SecuritySettings.getDefaultInstance() : securitySettings_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getSecuritySettings()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateMask()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getSecuritySettings()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest)) { return super.equals(obj); } com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest other = (com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest) obj; if (hasSecuritySettings() != other.hasSecuritySettings()) return false; if (hasSecuritySettings()) { if (!getSecuritySettings().equals(other.getSecuritySettings())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasSecuritySettings()) { hash = (37 * hash) + SECURITY_SETTINGS_FIELD_NUMBER; hash = (53 * hash) + getSecuritySettings().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request message for * [SecuritySettingsService.UpdateSecuritySettings][google.cloud.dialogflow.cx.v3.SecuritySettingsService.UpdateSecuritySettings]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest) com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3.SecuritySettingsProto .internal_static_google_cloud_dialogflow_cx_v3_UpdateSecuritySettingsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3.SecuritySettingsProto .internal_static_google_cloud_dialogflow_cx_v3_UpdateSecuritySettingsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest.class, com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest.Builder.class); } // Construct using com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getSecuritySettingsFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; securitySettings_ = null; if (securitySettingsBuilder_ != null) { securitySettingsBuilder_.dispose(); securitySettingsBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.cx.v3.SecuritySettingsProto .internal_static_google_cloud_dialogflow_cx_v3_UpdateSecuritySettingsRequest_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest getDefaultInstanceForType() { return com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest build() { com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest buildPartial() { com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest result = new com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.securitySettings_ = securitySettingsBuilder_ == null ? securitySettings_ : securitySettingsBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest) { return mergeFrom((com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest other) { if (other == com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest.getDefaultInstance()) return this; if (other.hasSecuritySettings()) { mergeSecuritySettings(other.getSecuritySettings()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage( getSecuritySettingsFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.dialogflow.cx.v3.SecuritySettings securitySettings_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.cx.v3.SecuritySettings, com.google.cloud.dialogflow.cx.v3.SecuritySettings.Builder, com.google.cloud.dialogflow.cx.v3.SecuritySettingsOrBuilder> securitySettingsBuilder_; /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the securitySettings field is set. */ public boolean hasSecuritySettings() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The securitySettings. */ public com.google.cloud.dialogflow.cx.v3.SecuritySettings getSecuritySettings() { if (securitySettingsBuilder_ == null) { return securitySettings_ == null ? com.google.cloud.dialogflow.cx.v3.SecuritySettings.getDefaultInstance() : securitySettings_; } else { return securitySettingsBuilder_.getMessage(); } } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSecuritySettings(com.google.cloud.dialogflow.cx.v3.SecuritySettings value) { if (securitySettingsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } securitySettings_ = value; } else { securitySettingsBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSecuritySettings( com.google.cloud.dialogflow.cx.v3.SecuritySettings.Builder builderForValue) { if (securitySettingsBuilder_ == null) { securitySettings_ = builderForValue.build(); } else { securitySettingsBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeSecuritySettings(com.google.cloud.dialogflow.cx.v3.SecuritySettings value) { if (securitySettingsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && securitySettings_ != null && securitySettings_ != com.google.cloud.dialogflow.cx.v3.SecuritySettings.getDefaultInstance()) { getSecuritySettingsBuilder().mergeFrom(value); } else { securitySettings_ = value; } } else { securitySettingsBuilder_.mergeFrom(value); } if (securitySettings_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearSecuritySettings() { bitField0_ = (bitField0_ & ~0x00000001); securitySettings_ = null; if (securitySettingsBuilder_ != null) { securitySettingsBuilder_.dispose(); securitySettingsBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dialogflow.cx.v3.SecuritySettings.Builder getSecuritySettingsBuilder() { bitField0_ |= 0x00000001; onChanged(); return getSecuritySettingsFieldBuilder().getBuilder(); } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dialogflow.cx.v3.SecuritySettingsOrBuilder getSecuritySettingsOrBuilder() { if (securitySettingsBuilder_ != null) { return securitySettingsBuilder_.getMessageOrBuilder(); } else { return securitySettings_ == null ? com.google.cloud.dialogflow.cx.v3.SecuritySettings.getDefaultInstance() : securitySettings_; } } /** * * * <pre> * Required. [SecuritySettings] object that contains values for each of the * fields to update. * </pre> * * <code> * .google.cloud.dialogflow.cx.v3.SecuritySettings security_settings = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.cx.v3.SecuritySettings, com.google.cloud.dialogflow.cx.v3.SecuritySettings.Builder, com.google.cloud.dialogflow.cx.v3.SecuritySettingsOrBuilder> getSecuritySettingsFieldBuilder() { if (securitySettingsBuilder_ == null) { securitySettingsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.cx.v3.SecuritySettings, com.google.cloud.dialogflow.cx.v3.SecuritySettings.Builder, com.google.cloud.dialogflow.cx.v3.SecuritySettingsOrBuilder>( getSecuritySettings(), getParentForChildren(), isClean()); securitySettings_ = null; } return securitySettingsBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest) private static final com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest(); } public static com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateSecuritySettingsRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateSecuritySettingsRequest>() { @java.lang.Override public UpdateSecuritySettingsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UpdateSecuritySettingsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateSecuritySettingsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3.UpdateSecuritySettingsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,608
java-batch/google-cloud-batch/src/main/java/com/google/cloud/batch/v1/stub/HttpJsonBatchServiceStub.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.batch.v1.stub; import static com.google.cloud.batch.v1.BatchServiceClient.ListJobsPagedResponse; import static com.google.cloud.batch.v1.BatchServiceClient.ListLocationsPagedResponse; import static com.google.cloud.batch.v1.BatchServiceClient.ListTasksPagedResponse; import com.google.api.HttpRule; import com.google.api.core.InternalApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.httpjson.ApiMethodDescriptor; import com.google.api.gax.httpjson.HttpJsonCallSettings; import com.google.api.gax.httpjson.HttpJsonOperationSnapshot; import com.google.api.gax.httpjson.HttpJsonStubCallableFactory; import com.google.api.gax.httpjson.ProtoMessageRequestFormatter; import com.google.api.gax.httpjson.ProtoMessageResponseParser; import com.google.api.gax.httpjson.ProtoRestSerializer; import com.google.api.gax.httpjson.longrunning.stub.HttpJsonOperationsStub; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.batch.v1.CancelJobRequest; import com.google.cloud.batch.v1.CancelJobResponse; import com.google.cloud.batch.v1.CreateJobRequest; import com.google.cloud.batch.v1.DeleteJobRequest; import com.google.cloud.batch.v1.GetJobRequest; import com.google.cloud.batch.v1.GetTaskRequest; import com.google.cloud.batch.v1.Job; import com.google.cloud.batch.v1.ListJobsRequest; import com.google.cloud.batch.v1.ListJobsResponse; import com.google.cloud.batch.v1.ListTasksRequest; import com.google.cloud.batch.v1.ListTasksResponse; import com.google.cloud.batch.v1.OperationMetadata; import com.google.cloud.batch.v1.Task; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.collect.ImmutableMap; import com.google.longrunning.Operation; import com.google.protobuf.Empty; import com.google.protobuf.TypeRegistry; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * REST stub implementation for the BatchService service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public class HttpJsonBatchServiceStub extends BatchServiceStub { private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder() .add(Empty.getDescriptor()) .add(OperationMetadata.getDescriptor()) .add(CancelJobResponse.getDescriptor()) .build(); private static final ApiMethodDescriptor<CreateJobRequest, Job> createJobMethodDescriptor = ApiMethodDescriptor.<CreateJobRequest, Job>newBuilder() .setFullMethodName("google.cloud.batch.v1.BatchService/CreateJob") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<CreateJobRequest>newBuilder() .setPath( "/v1/{parent=projects/*/locations/*}/jobs", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CreateJobRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CreateJobRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "jobId", request.getJobId()); serializer.putQueryParam(fields, "requestId", request.getRequestId()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create().toBody("job", request.getJob(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Job>newBuilder() .setDefaultInstance(Job.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetJobRequest, Job> getJobMethodDescriptor = ApiMethodDescriptor.<GetJobRequest, Job>newBuilder() .setFullMethodName("google.cloud.batch.v1.BatchService/GetJob") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetJobRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*/jobs/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetJobRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetJobRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Job>newBuilder() .setDefaultInstance(Job.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<DeleteJobRequest, Operation> deleteJobMethodDescriptor = ApiMethodDescriptor.<DeleteJobRequest, Operation>newBuilder() .setFullMethodName("google.cloud.batch.v1.BatchService/DeleteJob") .setHttpMethod("DELETE") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<DeleteJobRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*/jobs/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<DeleteJobRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<DeleteJobRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "reason", request.getReason()); serializer.putQueryParam(fields, "requestId", request.getRequestId()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (DeleteJobRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<CancelJobRequest, Operation> cancelJobMethodDescriptor = ApiMethodDescriptor.<CancelJobRequest, Operation>newBuilder() .setFullMethodName("google.cloud.batch.v1.BatchService/CancelJob") .setHttpMethod("POST") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<CancelJobRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*/jobs/*}:cancel", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<CancelJobRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<CancelJobRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor( request -> ProtoRestSerializer.create() .toBody("*", request.toBuilder().clearName().build(), true)) .build()) .setResponseParser( ProtoMessageResponseParser.<Operation>newBuilder() .setDefaultInstance(Operation.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .setOperationSnapshotFactory( (CancelJobRequest request, Operation response) -> HttpJsonOperationSnapshot.create(response)) .build(); private static final ApiMethodDescriptor<ListJobsRequest, ListJobsResponse> listJobsMethodDescriptor = ApiMethodDescriptor.<ListJobsRequest, ListJobsResponse>newBuilder() .setFullMethodName("google.cloud.batch.v1.BatchService/ListJobs") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListJobsRequest>newBuilder() .setPath( "/v1/{parent=projects/*/locations/*}/jobs", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListJobsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListJobsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "filter", request.getFilter()); serializer.putQueryParam(fields, "orderBy", request.getOrderBy()); serializer.putQueryParam(fields, "pageSize", request.getPageSize()); serializer.putQueryParam(fields, "pageToken", request.getPageToken()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListJobsResponse>newBuilder() .setDefaultInstance(ListJobsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetTaskRequest, Task> getTaskMethodDescriptor = ApiMethodDescriptor.<GetTaskRequest, Task>newBuilder() .setFullMethodName("google.cloud.batch.v1.BatchService/GetTask") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetTaskRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*/jobs/*/taskGroups/*/tasks/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetTaskRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetTaskRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Task>newBuilder() .setDefaultInstance(Task.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<ListTasksRequest, ListTasksResponse> listTasksMethodDescriptor = ApiMethodDescriptor.<ListTasksRequest, ListTasksResponse>newBuilder() .setFullMethodName("google.cloud.batch.v1.BatchService/ListTasks") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListTasksRequest>newBuilder() .setPath( "/v1/{parent=projects/*/locations/*/jobs/*/taskGroups/*}/tasks", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListTasksRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "parent", request.getParent()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListTasksRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "filter", request.getFilter()); serializer.putQueryParam(fields, "pageSize", request.getPageSize()); serializer.putQueryParam(fields, "pageToken", request.getPageToken()); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListTasksResponse>newBuilder() .setDefaultInstance(ListTasksResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<ListLocationsRequest, ListLocationsResponse> listLocationsMethodDescriptor = ApiMethodDescriptor.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setFullMethodName("google.cloud.location.Locations/ListLocations") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<ListLocationsRequest>newBuilder() .setPath( "/v1/{name=projects/*}/locations", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<ListLocationsRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<ListLocationsRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<ListLocationsResponse>newBuilder() .setDefaultInstance(ListLocationsResponse.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private static final ApiMethodDescriptor<GetLocationRequest, Location> getLocationMethodDescriptor = ApiMethodDescriptor.<GetLocationRequest, Location>newBuilder() .setFullMethodName("google.cloud.location.Locations/GetLocation") .setHttpMethod("GET") .setType(ApiMethodDescriptor.MethodType.UNARY) .setRequestFormatter( ProtoMessageRequestFormatter.<GetLocationRequest>newBuilder() .setPath( "/v1/{name=projects/*/locations/*}", request -> { Map<String, String> fields = new HashMap<>(); ProtoRestSerializer<GetLocationRequest> serializer = ProtoRestSerializer.create(); serializer.putPathParam(fields, "name", request.getName()); return fields; }) .setQueryParamsExtractor( request -> { Map<String, List<String>> fields = new HashMap<>(); ProtoRestSerializer<GetLocationRequest> serializer = ProtoRestSerializer.create(); serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int"); return fields; }) .setRequestBodyExtractor(request -> null) .build()) .setResponseParser( ProtoMessageResponseParser.<Location>newBuilder() .setDefaultInstance(Location.getDefaultInstance()) .setDefaultTypeRegistry(typeRegistry) .build()) .build(); private final UnaryCallable<CreateJobRequest, Job> createJobCallable; private final UnaryCallable<GetJobRequest, Job> getJobCallable; private final UnaryCallable<DeleteJobRequest, Operation> deleteJobCallable; private final OperationCallable<DeleteJobRequest, Empty, OperationMetadata> deleteJobOperationCallable; private final UnaryCallable<CancelJobRequest, Operation> cancelJobCallable; private final OperationCallable<CancelJobRequest, CancelJobResponse, OperationMetadata> cancelJobOperationCallable; private final UnaryCallable<ListJobsRequest, ListJobsResponse> listJobsCallable; private final UnaryCallable<ListJobsRequest, ListJobsPagedResponse> listJobsPagedCallable; private final UnaryCallable<GetTaskRequest, Task> getTaskCallable; private final UnaryCallable<ListTasksRequest, ListTasksResponse> listTasksCallable; private final UnaryCallable<ListTasksRequest, ListTasksPagedResponse> listTasksPagedCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable; private final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable; private final UnaryCallable<GetLocationRequest, Location> getLocationCallable; private final BackgroundResource backgroundResources; private final HttpJsonOperationsStub httpJsonOperationsStub; private final HttpJsonStubCallableFactory callableFactory; public static final HttpJsonBatchServiceStub create(BatchServiceStubSettings settings) throws IOException { return new HttpJsonBatchServiceStub(settings, ClientContext.create(settings)); } public static final HttpJsonBatchServiceStub create(ClientContext clientContext) throws IOException { return new HttpJsonBatchServiceStub( BatchServiceStubSettings.newHttpJsonBuilder().build(), clientContext); } public static final HttpJsonBatchServiceStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonBatchServiceStub( BatchServiceStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of HttpJsonBatchServiceStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonBatchServiceStub(BatchServiceStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new HttpJsonBatchServiceCallableFactory()); } /** * Constructs an instance of HttpJsonBatchServiceStub, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected HttpJsonBatchServiceStub( BatchServiceStubSettings settings, ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.httpJsonOperationsStub = HttpJsonOperationsStub.create( clientContext, callableFactory, typeRegistry, ImmutableMap.<String, HttpRule>builder() .put( "google.longrunning.Operations.CancelOperation", HttpRule.newBuilder() .setPost("/v1/{name=projects/*/locations/*/operations/*}:cancel") .build()) .put( "google.longrunning.Operations.DeleteOperation", HttpRule.newBuilder() .setDelete("/v1/{name=projects/*/locations/*/operations/*}") .build()) .put( "google.longrunning.Operations.GetOperation", HttpRule.newBuilder() .setGet("/v1/{name=projects/*/locations/*/operations/*}") .build()) .put( "google.longrunning.Operations.ListOperations", HttpRule.newBuilder() .setGet("/v1/{name=projects/*/locations/*}/operations") .build()) .build()); HttpJsonCallSettings<CreateJobRequest, Job> createJobTransportSettings = HttpJsonCallSettings.<CreateJobRequest, Job>newBuilder() .setMethodDescriptor(createJobMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings<GetJobRequest, Job> getJobTransportSettings = HttpJsonCallSettings.<GetJobRequest, Job>newBuilder() .setMethodDescriptor(getJobMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<DeleteJobRequest, Operation> deleteJobTransportSettings = HttpJsonCallSettings.<DeleteJobRequest, Operation>newBuilder() .setMethodDescriptor(deleteJobMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<CancelJobRequest, Operation> cancelJobTransportSettings = HttpJsonCallSettings.<CancelJobRequest, Operation>newBuilder() .setMethodDescriptor(cancelJobMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<ListJobsRequest, ListJobsResponse> listJobsTransportSettings = HttpJsonCallSettings.<ListJobsRequest, ListJobsResponse>newBuilder() .setMethodDescriptor(listJobsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings<GetTaskRequest, Task> getTaskTransportSettings = HttpJsonCallSettings.<GetTaskRequest, Task>newBuilder() .setMethodDescriptor(getTaskMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<ListTasksRequest, ListTasksResponse> listTasksTransportSettings = HttpJsonCallSettings.<ListTasksRequest, ListTasksResponse>newBuilder() .setMethodDescriptor(listTasksMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); HttpJsonCallSettings<ListLocationsRequest, ListLocationsResponse> listLocationsTransportSettings = HttpJsonCallSettings.<ListLocationsRequest, ListLocationsResponse>newBuilder() .setMethodDescriptor(listLocationsMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); HttpJsonCallSettings<GetLocationRequest, Location> getLocationTransportSettings = HttpJsonCallSettings.<GetLocationRequest, Location>newBuilder() .setMethodDescriptor(getLocationMethodDescriptor) .setTypeRegistry(typeRegistry) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); this.createJobCallable = callableFactory.createUnaryCallable( createJobTransportSettings, settings.createJobSettings(), clientContext); this.getJobCallable = callableFactory.createUnaryCallable( getJobTransportSettings, settings.getJobSettings(), clientContext); this.deleteJobCallable = callableFactory.createUnaryCallable( deleteJobTransportSettings, settings.deleteJobSettings(), clientContext); this.deleteJobOperationCallable = callableFactory.createOperationCallable( deleteJobTransportSettings, settings.deleteJobOperationSettings(), clientContext, httpJsonOperationsStub); this.cancelJobCallable = callableFactory.createUnaryCallable( cancelJobTransportSettings, settings.cancelJobSettings(), clientContext); this.cancelJobOperationCallable = callableFactory.createOperationCallable( cancelJobTransportSettings, settings.cancelJobOperationSettings(), clientContext, httpJsonOperationsStub); this.listJobsCallable = callableFactory.createUnaryCallable( listJobsTransportSettings, settings.listJobsSettings(), clientContext); this.listJobsPagedCallable = callableFactory.createPagedCallable( listJobsTransportSettings, settings.listJobsSettings(), clientContext); this.getTaskCallable = callableFactory.createUnaryCallable( getTaskTransportSettings, settings.getTaskSettings(), clientContext); this.listTasksCallable = callableFactory.createUnaryCallable( listTasksTransportSettings, settings.listTasksSettings(), clientContext); this.listTasksPagedCallable = callableFactory.createPagedCallable( listTasksTransportSettings, settings.listTasksSettings(), clientContext); this.listLocationsCallable = callableFactory.createUnaryCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.listLocationsPagedCallable = callableFactory.createPagedCallable( listLocationsTransportSettings, settings.listLocationsSettings(), clientContext); this.getLocationCallable = callableFactory.createUnaryCallable( getLocationTransportSettings, settings.getLocationSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } @InternalApi public static List<ApiMethodDescriptor> getMethodDescriptors() { List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>(); methodDescriptors.add(createJobMethodDescriptor); methodDescriptors.add(getJobMethodDescriptor); methodDescriptors.add(deleteJobMethodDescriptor); methodDescriptors.add(cancelJobMethodDescriptor); methodDescriptors.add(listJobsMethodDescriptor); methodDescriptors.add(getTaskMethodDescriptor); methodDescriptors.add(listTasksMethodDescriptor); methodDescriptors.add(listLocationsMethodDescriptor); methodDescriptors.add(getLocationMethodDescriptor); return methodDescriptors; } public HttpJsonOperationsStub getHttpJsonOperationsStub() { return httpJsonOperationsStub; } @Override public UnaryCallable<CreateJobRequest, Job> createJobCallable() { return createJobCallable; } @Override public UnaryCallable<GetJobRequest, Job> getJobCallable() { return getJobCallable; } @Override public UnaryCallable<DeleteJobRequest, Operation> deleteJobCallable() { return deleteJobCallable; } @Override public OperationCallable<DeleteJobRequest, Empty, OperationMetadata> deleteJobOperationCallable() { return deleteJobOperationCallable; } @Override public UnaryCallable<CancelJobRequest, Operation> cancelJobCallable() { return cancelJobCallable; } @Override public OperationCallable<CancelJobRequest, CancelJobResponse, OperationMetadata> cancelJobOperationCallable() { return cancelJobOperationCallable; } @Override public UnaryCallable<ListJobsRequest, ListJobsResponse> listJobsCallable() { return listJobsCallable; } @Override public UnaryCallable<ListJobsRequest, ListJobsPagedResponse> listJobsPagedCallable() { return listJobsPagedCallable; } @Override public UnaryCallable<GetTaskRequest, Task> getTaskCallable() { return getTaskCallable; } @Override public UnaryCallable<ListTasksRequest, ListTasksResponse> listTasksCallable() { return listTasksCallable; } @Override public UnaryCallable<ListTasksRequest, ListTasksPagedResponse> listTasksPagedCallable() { return listTasksPagedCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return listLocationsCallable; } @Override public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return listLocationsPagedCallable; } @Override public UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return getLocationCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
googleapis/google-cloud-java
36,353
java-service-usage/proto-google-cloud-service-usage-v1beta1/src/main/java/com/google/api/serviceusage/v1beta1/ListServicesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/serviceusage/v1beta1/serviceusage.proto // Protobuf Java Version: 3.25.8 package com.google.api.serviceusage.v1beta1; /** * * * <pre> * Response message for the `ListServices` method. * </pre> * * Protobuf type {@code google.api.serviceusage.v1beta1.ListServicesResponse} */ public final class ListServicesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.api.serviceusage.v1beta1.ListServicesResponse) ListServicesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListServicesResponse.newBuilder() to construct. private ListServicesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListServicesResponse() { services_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListServicesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.serviceusage.v1beta1.ServiceUsageProto .internal_static_google_api_serviceusage_v1beta1_ListServicesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.serviceusage.v1beta1.ServiceUsageProto .internal_static_google_api_serviceusage_v1beta1_ListServicesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.serviceusage.v1beta1.ListServicesResponse.class, com.google.api.serviceusage.v1beta1.ListServicesResponse.Builder.class); } public static final int SERVICES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.api.serviceusage.v1beta1.Service> services_; /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ @java.lang.Override public java.util.List<com.google.api.serviceusage.v1beta1.Service> getServicesList() { return services_; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.api.serviceusage.v1beta1.ServiceOrBuilder> getServicesOrBuilderList() { return services_; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ @java.lang.Override public int getServicesCount() { return services_.size(); } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ @java.lang.Override public com.google.api.serviceusage.v1beta1.Service getServices(int index) { return services_.get(index); } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ @java.lang.Override public com.google.api.serviceusage.v1beta1.ServiceOrBuilder getServicesOrBuilder(int index) { return services_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token that can be passed to `ListServices` to resume a paginated * query. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Token that can be passed to `ListServices` to resume a paginated * query. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < services_.size(); i++) { output.writeMessage(1, services_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < services_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, services_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.api.serviceusage.v1beta1.ListServicesResponse)) { return super.equals(obj); } com.google.api.serviceusage.v1beta1.ListServicesResponse other = (com.google.api.serviceusage.v1beta1.ListServicesResponse) obj; if (!getServicesList().equals(other.getServicesList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getServicesCount() > 0) { hash = (37 * hash) + SERVICES_FIELD_NUMBER; hash = (53 * hash) + getServicesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.api.serviceusage.v1beta1.ListServicesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for the `ListServices` method. * </pre> * * Protobuf type {@code google.api.serviceusage.v1beta1.ListServicesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.api.serviceusage.v1beta1.ListServicesResponse) com.google.api.serviceusage.v1beta1.ListServicesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.serviceusage.v1beta1.ServiceUsageProto .internal_static_google_api_serviceusage_v1beta1_ListServicesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.serviceusage.v1beta1.ServiceUsageProto .internal_static_google_api_serviceusage_v1beta1_ListServicesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.serviceusage.v1beta1.ListServicesResponse.class, com.google.api.serviceusage.v1beta1.ListServicesResponse.Builder.class); } // Construct using com.google.api.serviceusage.v1beta1.ListServicesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (servicesBuilder_ == null) { services_ = java.util.Collections.emptyList(); } else { services_ = null; servicesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.api.serviceusage.v1beta1.ServiceUsageProto .internal_static_google_api_serviceusage_v1beta1_ListServicesResponse_descriptor; } @java.lang.Override public com.google.api.serviceusage.v1beta1.ListServicesResponse getDefaultInstanceForType() { return com.google.api.serviceusage.v1beta1.ListServicesResponse.getDefaultInstance(); } @java.lang.Override public com.google.api.serviceusage.v1beta1.ListServicesResponse build() { com.google.api.serviceusage.v1beta1.ListServicesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.api.serviceusage.v1beta1.ListServicesResponse buildPartial() { com.google.api.serviceusage.v1beta1.ListServicesResponse result = new com.google.api.serviceusage.v1beta1.ListServicesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.api.serviceusage.v1beta1.ListServicesResponse result) { if (servicesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { services_ = java.util.Collections.unmodifiableList(services_); bitField0_ = (bitField0_ & ~0x00000001); } result.services_ = services_; } else { result.services_ = servicesBuilder_.build(); } } private void buildPartial0(com.google.api.serviceusage.v1beta1.ListServicesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.api.serviceusage.v1beta1.ListServicesResponse) { return mergeFrom((com.google.api.serviceusage.v1beta1.ListServicesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.api.serviceusage.v1beta1.ListServicesResponse other) { if (other == com.google.api.serviceusage.v1beta1.ListServicesResponse.getDefaultInstance()) return this; if (servicesBuilder_ == null) { if (!other.services_.isEmpty()) { if (services_.isEmpty()) { services_ = other.services_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureServicesIsMutable(); services_.addAll(other.services_); } onChanged(); } } else { if (!other.services_.isEmpty()) { if (servicesBuilder_.isEmpty()) { servicesBuilder_.dispose(); servicesBuilder_ = null; services_ = other.services_; bitField0_ = (bitField0_ & ~0x00000001); servicesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getServicesFieldBuilder() : null; } else { servicesBuilder_.addAllMessages(other.services_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.api.serviceusage.v1beta1.Service m = input.readMessage( com.google.api.serviceusage.v1beta1.Service.parser(), extensionRegistry); if (servicesBuilder_ == null) { ensureServicesIsMutable(); services_.add(m); } else { servicesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.api.serviceusage.v1beta1.Service> services_ = java.util.Collections.emptyList(); private void ensureServicesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { services_ = new java.util.ArrayList<com.google.api.serviceusage.v1beta1.Service>(services_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.api.serviceusage.v1beta1.Service, com.google.api.serviceusage.v1beta1.Service.Builder, com.google.api.serviceusage.v1beta1.ServiceOrBuilder> servicesBuilder_; /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public java.util.List<com.google.api.serviceusage.v1beta1.Service> getServicesList() { if (servicesBuilder_ == null) { return java.util.Collections.unmodifiableList(services_); } else { return servicesBuilder_.getMessageList(); } } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public int getServicesCount() { if (servicesBuilder_ == null) { return services_.size(); } else { return servicesBuilder_.getCount(); } } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public com.google.api.serviceusage.v1beta1.Service getServices(int index) { if (servicesBuilder_ == null) { return services_.get(index); } else { return servicesBuilder_.getMessage(index); } } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder setServices(int index, com.google.api.serviceusage.v1beta1.Service value) { if (servicesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServicesIsMutable(); services_.set(index, value); onChanged(); } else { servicesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder setServices( int index, com.google.api.serviceusage.v1beta1.Service.Builder builderForValue) { if (servicesBuilder_ == null) { ensureServicesIsMutable(); services_.set(index, builderForValue.build()); onChanged(); } else { servicesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder addServices(com.google.api.serviceusage.v1beta1.Service value) { if (servicesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServicesIsMutable(); services_.add(value); onChanged(); } else { servicesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder addServices(int index, com.google.api.serviceusage.v1beta1.Service value) { if (servicesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServicesIsMutable(); services_.add(index, value); onChanged(); } else { servicesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder addServices( com.google.api.serviceusage.v1beta1.Service.Builder builderForValue) { if (servicesBuilder_ == null) { ensureServicesIsMutable(); services_.add(builderForValue.build()); onChanged(); } else { servicesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder addServices( int index, com.google.api.serviceusage.v1beta1.Service.Builder builderForValue) { if (servicesBuilder_ == null) { ensureServicesIsMutable(); services_.add(index, builderForValue.build()); onChanged(); } else { servicesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder addAllServices( java.lang.Iterable<? extends com.google.api.serviceusage.v1beta1.Service> values) { if (servicesBuilder_ == null) { ensureServicesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, services_); onChanged(); } else { servicesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder clearServices() { if (servicesBuilder_ == null) { services_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { servicesBuilder_.clear(); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public Builder removeServices(int index) { if (servicesBuilder_ == null) { ensureServicesIsMutable(); services_.remove(index); onChanged(); } else { servicesBuilder_.remove(index); } return this; } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public com.google.api.serviceusage.v1beta1.Service.Builder getServicesBuilder(int index) { return getServicesFieldBuilder().getBuilder(index); } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public com.google.api.serviceusage.v1beta1.ServiceOrBuilder getServicesOrBuilder(int index) { if (servicesBuilder_ == null) { return services_.get(index); } else { return servicesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public java.util.List<? extends com.google.api.serviceusage.v1beta1.ServiceOrBuilder> getServicesOrBuilderList() { if (servicesBuilder_ != null) { return servicesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(services_); } } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public com.google.api.serviceusage.v1beta1.Service.Builder addServicesBuilder() { return getServicesFieldBuilder() .addBuilder(com.google.api.serviceusage.v1beta1.Service.getDefaultInstance()); } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public com.google.api.serviceusage.v1beta1.Service.Builder addServicesBuilder(int index) { return getServicesFieldBuilder() .addBuilder(index, com.google.api.serviceusage.v1beta1.Service.getDefaultInstance()); } /** * * * <pre> * The available services for the requested project. * </pre> * * <code>repeated .google.api.serviceusage.v1beta1.Service services = 1;</code> */ public java.util.List<com.google.api.serviceusage.v1beta1.Service.Builder> getServicesBuilderList() { return getServicesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.api.serviceusage.v1beta1.Service, com.google.api.serviceusage.v1beta1.Service.Builder, com.google.api.serviceusage.v1beta1.ServiceOrBuilder> getServicesFieldBuilder() { if (servicesBuilder_ == null) { servicesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.api.serviceusage.v1beta1.Service, com.google.api.serviceusage.v1beta1.Service.Builder, com.google.api.serviceusage.v1beta1.ServiceOrBuilder>( services_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); services_ = null; } return servicesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token that can be passed to `ListServices` to resume a paginated * query. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Token that can be passed to `ListServices` to resume a paginated * query. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Token that can be passed to `ListServices` to resume a paginated * query. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Token that can be passed to `ListServices` to resume a paginated * query. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Token that can be passed to `ListServices` to resume a paginated * query. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.api.serviceusage.v1beta1.ListServicesResponse) } // @@protoc_insertion_point(class_scope:google.api.serviceusage.v1beta1.ListServicesResponse) private static final com.google.api.serviceusage.v1beta1.ListServicesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.api.serviceusage.v1beta1.ListServicesResponse(); } public static com.google.api.serviceusage.v1beta1.ListServicesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListServicesResponse> PARSER = new com.google.protobuf.AbstractParser<ListServicesResponse>() { @java.lang.Override public ListServicesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListServicesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListServicesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.api.serviceusage.v1beta1.ListServicesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,653
java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/AddressesStubSettings.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.compute.v1.stub; import static com.google.cloud.compute.v1.AddressesClient.AggregatedListPagedResponse; import static com.google.cloud.compute.v1.AddressesClient.ListPagedResponse; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.httpjson.GaxHttpJsonProperties; import com.google.api.gax.httpjson.HttpJsonTransportChannel; import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider; import com.google.api.gax.httpjson.ProtoOperationTransformers; import com.google.api.gax.longrunning.OperationSnapshot; import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.PagedListDescriptor; import com.google.api.gax.rpc.PagedListResponseFactory; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.compute.v1.Address; import com.google.cloud.compute.v1.AddressAggregatedList; import com.google.cloud.compute.v1.AddressList; import com.google.cloud.compute.v1.AddressesScopedList; import com.google.cloud.compute.v1.AggregatedListAddressesRequest; import com.google.cloud.compute.v1.DeleteAddressRequest; import com.google.cloud.compute.v1.GetAddressRequest; import com.google.cloud.compute.v1.InsertAddressRequest; import com.google.cloud.compute.v1.ListAddressesRequest; import com.google.cloud.compute.v1.MoveAddressRequest; import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.SetLabelsAddressRequest; import com.google.cloud.compute.v1.TestIamPermissionsAddressRequest; import com.google.cloud.compute.v1.TestPermissionsResponse; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import java.io.IOException; import java.time.Duration; import java.util.List; import java.util.Map; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link AddressesStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (compute.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the * [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings) * of get: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * AddressesStubSettings.Builder addressesSettingsBuilder = AddressesStubSettings.newBuilder(); * addressesSettingsBuilder * .getSettings() * .setRetrySettings( * addressesSettingsBuilder * .getSettings() * .getRetrySettings() * .toBuilder() * .setInitialRetryDelayDuration(Duration.ofSeconds(1)) * .setInitialRpcTimeoutDuration(Duration.ofSeconds(5)) * .setMaxAttempts(5) * .setMaxRetryDelayDuration(Duration.ofSeconds(30)) * .setMaxRpcTimeoutDuration(Duration.ofSeconds(60)) * .setRetryDelayMultiplier(1.3) * .setRpcTimeoutMultiplier(1.5) * .setTotalTimeoutDuration(Duration.ofSeconds(300)) * .build()); * AddressesStubSettings addressesSettings = addressesSettingsBuilder.build(); * }</pre> * * Please refer to the [Client Side Retry * Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for * additional support in setting retries. * * <p>To configure the RetrySettings of a Long Running Operation method, create an * OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to * configure the RetrySettings for delete: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * AddressesStubSettings.Builder addressesSettingsBuilder = AddressesStubSettings.newBuilder(); * TimedRetryAlgorithm timedRetryAlgorithm = * OperationalTimedPollAlgorithm.create( * RetrySettings.newBuilder() * .setInitialRetryDelayDuration(Duration.ofMillis(500)) * .setRetryDelayMultiplier(1.5) * .setMaxRetryDelayDuration(Duration.ofMillis(5000)) * .setTotalTimeoutDuration(Duration.ofHours(24)) * .build()); * addressesSettingsBuilder * .createClusterOperationSettings() * .setPollingAlgorithm(timedRetryAlgorithm) * .build(); * }</pre> */ @Generated("by gapic-generator-java") public class AddressesStubSettings extends StubSettings<AddressesStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder() .add("https://www.googleapis.com/auth/compute") .add("https://www.googleapis.com/auth/cloud-platform") .build(); private final PagedCallSettings< AggregatedListAddressesRequest, AddressAggregatedList, AggregatedListPagedResponse> aggregatedListSettings; private final UnaryCallSettings<DeleteAddressRequest, Operation> deleteSettings; private final OperationCallSettings<DeleteAddressRequest, Operation, Operation> deleteOperationSettings; private final UnaryCallSettings<GetAddressRequest, Address> getSettings; private final UnaryCallSettings<InsertAddressRequest, Operation> insertSettings; private final OperationCallSettings<InsertAddressRequest, Operation, Operation> insertOperationSettings; private final PagedCallSettings<ListAddressesRequest, AddressList, ListPagedResponse> listSettings; private final UnaryCallSettings<MoveAddressRequest, Operation> moveSettings; private final OperationCallSettings<MoveAddressRequest, Operation, Operation> moveOperationSettings; private final UnaryCallSettings<SetLabelsAddressRequest, Operation> setLabelsSettings; private final OperationCallSettings<SetLabelsAddressRequest, Operation, Operation> setLabelsOperationSettings; private final UnaryCallSettings<TestIamPermissionsAddressRequest, TestPermissionsResponse> testIamPermissionsSettings; private static final PagedListDescriptor< AggregatedListAddressesRequest, AddressAggregatedList, Map.Entry<String, AddressesScopedList>> AGGREGATED_LIST_PAGE_STR_DESC = new PagedListDescriptor< AggregatedListAddressesRequest, AddressAggregatedList, Map.Entry<String, AddressesScopedList>>() { @Override public String emptyToken() { return ""; } @Override public AggregatedListAddressesRequest injectToken( AggregatedListAddressesRequest payload, String token) { return AggregatedListAddressesRequest.newBuilder(payload).setPageToken(token).build(); } @Override public AggregatedListAddressesRequest injectPageSize( AggregatedListAddressesRequest payload, int pageSize) { return AggregatedListAddressesRequest.newBuilder(payload) .setMaxResults(pageSize) .build(); } @Override public Integer extractPageSize(AggregatedListAddressesRequest payload) { return payload.getMaxResults(); } @Override public String extractNextToken(AddressAggregatedList payload) { return payload.getNextPageToken(); } @Override public Iterable<Map.Entry<String, AddressesScopedList>> extractResources( AddressAggregatedList payload) { return payload.getItemsMap().entrySet(); } }; private static final PagedListDescriptor<ListAddressesRequest, AddressList, Address> LIST_PAGE_STR_DESC = new PagedListDescriptor<ListAddressesRequest, AddressList, Address>() { @Override public String emptyToken() { return ""; } @Override public ListAddressesRequest injectToken(ListAddressesRequest payload, String token) { return ListAddressesRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListAddressesRequest injectPageSize(ListAddressesRequest payload, int pageSize) { return ListAddressesRequest.newBuilder(payload).setMaxResults(pageSize).build(); } @Override public Integer extractPageSize(ListAddressesRequest payload) { return payload.getMaxResults(); } @Override public String extractNextToken(AddressList payload) { return payload.getNextPageToken(); } @Override public Iterable<Address> extractResources(AddressList payload) { return payload.getItemsList(); } }; private static final PagedListResponseFactory< AggregatedListAddressesRequest, AddressAggregatedList, AggregatedListPagedResponse> AGGREGATED_LIST_PAGE_STR_FACT = new PagedListResponseFactory< AggregatedListAddressesRequest, AddressAggregatedList, AggregatedListPagedResponse>() { @Override public ApiFuture<AggregatedListPagedResponse> getFuturePagedResponse( UnaryCallable<AggregatedListAddressesRequest, AddressAggregatedList> callable, AggregatedListAddressesRequest request, ApiCallContext context, ApiFuture<AddressAggregatedList> futureResponse) { PageContext< AggregatedListAddressesRequest, AddressAggregatedList, Map.Entry<String, AddressesScopedList>> pageContext = PageContext.create(callable, AGGREGATED_LIST_PAGE_STR_DESC, request, context); return AggregatedListPagedResponse.createAsync(pageContext, futureResponse); } }; private static final PagedListResponseFactory< ListAddressesRequest, AddressList, ListPagedResponse> LIST_PAGE_STR_FACT = new PagedListResponseFactory<ListAddressesRequest, AddressList, ListPagedResponse>() { @Override public ApiFuture<ListPagedResponse> getFuturePagedResponse( UnaryCallable<ListAddressesRequest, AddressList> callable, ListAddressesRequest request, ApiCallContext context, ApiFuture<AddressList> futureResponse) { PageContext<ListAddressesRequest, AddressList, Address> pageContext = PageContext.create(callable, LIST_PAGE_STR_DESC, request, context); return ListPagedResponse.createAsync(pageContext, futureResponse); } }; /** Returns the object with the settings used for calls to aggregatedList. */ public PagedCallSettings< AggregatedListAddressesRequest, AddressAggregatedList, AggregatedListPagedResponse> aggregatedListSettings() { return aggregatedListSettings; } /** Returns the object with the settings used for calls to delete. */ public UnaryCallSettings<DeleteAddressRequest, Operation> deleteSettings() { return deleteSettings; } /** Returns the object with the settings used for calls to delete. */ public OperationCallSettings<DeleteAddressRequest, Operation, Operation> deleteOperationSettings() { return deleteOperationSettings; } /** Returns the object with the settings used for calls to get. */ public UnaryCallSettings<GetAddressRequest, Address> getSettings() { return getSettings; } /** Returns the object with the settings used for calls to insert. */ public UnaryCallSettings<InsertAddressRequest, Operation> insertSettings() { return insertSettings; } /** Returns the object with the settings used for calls to insert. */ public OperationCallSettings<InsertAddressRequest, Operation, Operation> insertOperationSettings() { return insertOperationSettings; } /** Returns the object with the settings used for calls to list. */ public PagedCallSettings<ListAddressesRequest, AddressList, ListPagedResponse> listSettings() { return listSettings; } /** Returns the object with the settings used for calls to move. */ public UnaryCallSettings<MoveAddressRequest, Operation> moveSettings() { return moveSettings; } /** Returns the object with the settings used for calls to move. */ public OperationCallSettings<MoveAddressRequest, Operation, Operation> moveOperationSettings() { return moveOperationSettings; } /** Returns the object with the settings used for calls to setLabels. */ public UnaryCallSettings<SetLabelsAddressRequest, Operation> setLabelsSettings() { return setLabelsSettings; } /** Returns the object with the settings used for calls to setLabels. */ public OperationCallSettings<SetLabelsAddressRequest, Operation, Operation> setLabelsOperationSettings() { return setLabelsOperationSettings; } /** Returns the object with the settings used for calls to testIamPermissions. */ public UnaryCallSettings<TestIamPermissionsAddressRequest, TestPermissionsResponse> testIamPermissionsSettings() { return testIamPermissionsSettings; } public AddressesStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { return HttpJsonAddressesStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns the default service name. */ @Override public String getServiceName() { return "compute"; } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ @ObsoleteApi("Use getEndpoint() instead") public static String getDefaultEndpoint() { return "compute.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "compute.mtls.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder() .setScopesToApply(DEFAULT_SERVICE_SCOPES) .setUseJwtAccessWithScope(true); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingHttpJsonChannelProvider.Builder defaultHttpJsonTransportProviderBuilder() { return InstantiatingHttpJsonChannelProvider.newBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultHttpJsonTransportProviderBuilder().build(); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(AddressesStubSettings.class)) .setTransportToken( GaxHttpJsonProperties.getHttpJsonTokenName(), GaxHttpJsonProperties.getHttpJsonVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected AddressesStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); aggregatedListSettings = settingsBuilder.aggregatedListSettings().build(); deleteSettings = settingsBuilder.deleteSettings().build(); deleteOperationSettings = settingsBuilder.deleteOperationSettings().build(); getSettings = settingsBuilder.getSettings().build(); insertSettings = settingsBuilder.insertSettings().build(); insertOperationSettings = settingsBuilder.insertOperationSettings().build(); listSettings = settingsBuilder.listSettings().build(); moveSettings = settingsBuilder.moveSettings().build(); moveOperationSettings = settingsBuilder.moveOperationSettings().build(); setLabelsSettings = settingsBuilder.setLabelsSettings().build(); setLabelsOperationSettings = settingsBuilder.setLabelsOperationSettings().build(); testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build(); } /** Builder for AddressesStubSettings. */ public static class Builder extends StubSettings.Builder<AddressesStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final PagedCallSettings.Builder< AggregatedListAddressesRequest, AddressAggregatedList, AggregatedListPagedResponse> aggregatedListSettings; private final UnaryCallSettings.Builder<DeleteAddressRequest, Operation> deleteSettings; private final OperationCallSettings.Builder<DeleteAddressRequest, Operation, Operation> deleteOperationSettings; private final UnaryCallSettings.Builder<GetAddressRequest, Address> getSettings; private final UnaryCallSettings.Builder<InsertAddressRequest, Operation> insertSettings; private final OperationCallSettings.Builder<InsertAddressRequest, Operation, Operation> insertOperationSettings; private final PagedCallSettings.Builder<ListAddressesRequest, AddressList, ListPagedResponse> listSettings; private final UnaryCallSettings.Builder<MoveAddressRequest, Operation> moveSettings; private final OperationCallSettings.Builder<MoveAddressRequest, Operation, Operation> moveOperationSettings; private final UnaryCallSettings.Builder<SetLabelsAddressRequest, Operation> setLabelsSettings; private final OperationCallSettings.Builder<SetLabelsAddressRequest, Operation, Operation> setLabelsOperationSettings; private final UnaryCallSettings.Builder< TestIamPermissionsAddressRequest, TestPermissionsResponse> testIamPermissionsSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "retry_policy_0_codes", ImmutableSet.copyOf( Lists.<StatusCode.Code>newArrayList( StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE))); definitions.put( "no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList())); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(100L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelayDuration(Duration.ofMillis(60000L)) .setInitialRpcTimeoutDuration(Duration.ofMillis(600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ofMillis(600000L)) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build(); definitions.put("retry_policy_0_params", settings); settings = RetrySettings.newBuilder() .setInitialRpcTimeoutDuration(Duration.ofMillis(600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ofMillis(600000L)) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build(); definitions.put("no_retry_1_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); aggregatedListSettings = PagedCallSettings.newBuilder(AGGREGATED_LIST_PAGE_STR_FACT); deleteSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); deleteOperationSettings = OperationCallSettings.newBuilder(); getSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); insertSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); insertOperationSettings = OperationCallSettings.newBuilder(); listSettings = PagedCallSettings.newBuilder(LIST_PAGE_STR_FACT); moveSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); moveOperationSettings = OperationCallSettings.newBuilder(); setLabelsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); setLabelsOperationSettings = OperationCallSettings.newBuilder(); testIamPermissionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( aggregatedListSettings, deleteSettings, getSettings, insertSettings, listSettings, moveSettings, setLabelsSettings, testIamPermissionsSettings); initDefaults(this); } protected Builder(AddressesStubSettings settings) { super(settings); aggregatedListSettings = settings.aggregatedListSettings.toBuilder(); deleteSettings = settings.deleteSettings.toBuilder(); deleteOperationSettings = settings.deleteOperationSettings.toBuilder(); getSettings = settings.getSettings.toBuilder(); insertSettings = settings.insertSettings.toBuilder(); insertOperationSettings = settings.insertOperationSettings.toBuilder(); listSettings = settings.listSettings.toBuilder(); moveSettings = settings.moveSettings.toBuilder(); moveOperationSettings = settings.moveOperationSettings.toBuilder(); setLabelsSettings = settings.setLabelsSettings.toBuilder(); setLabelsOperationSettings = settings.setLabelsOperationSettings.toBuilder(); testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( aggregatedListSettings, deleteSettings, getSettings, insertSettings, listSettings, moveSettings, setLabelsSettings, testIamPermissionsSettings); } private static Builder createDefault() { Builder builder = new Builder(((ClientContext) null)); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .aggregatedListSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .deleteSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .getSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .insertSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .listSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .moveSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .setLabelsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .testIamPermissionsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .deleteOperationSettings() .setInitialCallSettings( UnaryCallSettings .<DeleteAddressRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); builder .insertOperationSettings() .setInitialCallSettings( UnaryCallSettings .<InsertAddressRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); builder .moveOperationSettings() .setInitialCallSettings( UnaryCallSettings.<MoveAddressRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); builder .setLabelsOperationSettings() .setInitialCallSettings( UnaryCallSettings .<SetLabelsAddressRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); return builder; } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to aggregatedList. */ public PagedCallSettings.Builder< AggregatedListAddressesRequest, AddressAggregatedList, AggregatedListPagedResponse> aggregatedListSettings() { return aggregatedListSettings; } /** Returns the builder for the settings used for calls to delete. */ public UnaryCallSettings.Builder<DeleteAddressRequest, Operation> deleteSettings() { return deleteSettings; } /** Returns the builder for the settings used for calls to delete. */ public OperationCallSettings.Builder<DeleteAddressRequest, Operation, Operation> deleteOperationSettings() { return deleteOperationSettings; } /** Returns the builder for the settings used for calls to get. */ public UnaryCallSettings.Builder<GetAddressRequest, Address> getSettings() { return getSettings; } /** Returns the builder for the settings used for calls to insert. */ public UnaryCallSettings.Builder<InsertAddressRequest, Operation> insertSettings() { return insertSettings; } /** Returns the builder for the settings used for calls to insert. */ public OperationCallSettings.Builder<InsertAddressRequest, Operation, Operation> insertOperationSettings() { return insertOperationSettings; } /** Returns the builder for the settings used for calls to list. */ public PagedCallSettings.Builder<ListAddressesRequest, AddressList, ListPagedResponse> listSettings() { return listSettings; } /** Returns the builder for the settings used for calls to move. */ public UnaryCallSettings.Builder<MoveAddressRequest, Operation> moveSettings() { return moveSettings; } /** Returns the builder for the settings used for calls to move. */ public OperationCallSettings.Builder<MoveAddressRequest, Operation, Operation> moveOperationSettings() { return moveOperationSettings; } /** Returns the builder for the settings used for calls to setLabels. */ public UnaryCallSettings.Builder<SetLabelsAddressRequest, Operation> setLabelsSettings() { return setLabelsSettings; } /** Returns the builder for the settings used for calls to setLabels. */ public OperationCallSettings.Builder<SetLabelsAddressRequest, Operation, Operation> setLabelsOperationSettings() { return setLabelsOperationSettings; } /** Returns the builder for the settings used for calls to testIamPermissions. */ public UnaryCallSettings.Builder<TestIamPermissionsAddressRequest, TestPermissionsResponse> testIamPermissionsSettings() { return testIamPermissionsSettings; } @Override public AddressesStubSettings build() throws IOException { return new AddressesStubSettings(this); } } }
apache/jspwiki
36,633
jspwiki-main/src/main/java/org/apache/wiki/references/DefaultReferenceManager.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.wiki.references; import org.apache.commons.lang3.time.StopWatch; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.wiki.InternalWikiException; import org.apache.wiki.LinkCollector; import org.apache.wiki.api.core.Attachment; import org.apache.wiki.api.core.Context; import org.apache.wiki.api.core.Engine; import org.apache.wiki.api.core.Page; import org.apache.wiki.api.exceptions.ProviderException; import org.apache.wiki.api.filters.BasePageFilter; import org.apache.wiki.api.providers.PageProvider; import org.apache.wiki.api.providers.WikiProvider; import org.apache.wiki.api.spi.Wiki; import org.apache.wiki.attachment.AttachmentManager; import org.apache.wiki.event.WikiEvent; import org.apache.wiki.event.WikiEventManager; import org.apache.wiki.event.WikiPageEvent; import org.apache.wiki.pages.PageManager; import org.apache.wiki.render.RenderingManager; import org.apache.wiki.util.TextUtil; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /* BUGS - if a wikilink is added to a page, then removed, RefMan still thinks that the page refers to the wikilink page. Hm. - if a page is deleted, gets very confused. - Serialization causes page attributes to be missing, when InitializablePlugins are not executed properly. Thus, serialization should really also mark whether a page is serializable or not... */ /* A word about synchronizing: I expect this object to be accessed in three situations: - when an Engine is created, and it scans its wikipages - when the Engine saves a page - when a JSP page accesses one of the Engine's ReferenceManagers to display a list of (un)referenced pages. So, access to this class is fairly rare, and usually triggered by user interaction. OTOH, the methods in this class use their storage objects intensively (and, sorry to say, in an unoptimized manner =). My deduction: using unsynchronized HashMaps etc. and syncing methods or code blocks is preferrable to using slow, synced storage objects. We don't have iterative code here, so I'm going to use synced methods for now. Please contact me if you notice problems with ReferenceManager, and especially with synchronization, or if you have suggestions about syncing. ebu@memecry.net */ /** * Keeps track of wikipage references: * <UL> * <LI>What pages a given page refers to * <LI>What pages refer to a given page * </UL> * * This is a quick'n'dirty approach without any finesse in storage and searching algorithms; we trust java.util.*. * <P> * This class contains two HashMaps, m_refersTo and m_referredBy. The first is indexed by WikiPage names and contains a Collection of all * WikiPages the page refers to. (Multiple references are not counted, naturally.) The second is indexed by WikiPage names and contains * a Set of all pages that refer to the indexing page. (Notice - the keys of both Maps should be kept in sync.) * <P> * When a page is added or edited, its references are parsed, a Collection is received, and we crudely replace anything previous with * this new Collection. We then check each referenced page name and make sure they know they are referred to by the new page. * <P> * Based on this information, we can perform non-optimal searches for e.g. unreferenced pages, top ten lists, etc. * <P> * The owning class must take responsibility of filling in any pre-existing information, probably by loading each and every WikiPage * and calling this class to update the references when created. * * @since 1.6.1 (as of 2.11.0, moved to org.apache.wiki.references) */ // FIXME: The way that we save attributes is now a major booboo, and must be // replaced forthwith. However, this is a workaround for the great deal // of problems that occur here... public class DefaultReferenceManager extends BasePageFilter implements ReferenceManager, Serializable { /** * Maps page wikiname to a Collection of pages it refers to. The Collection must contain Strings. The Collection may contain * names of non-existing pages. */ private Map< String, Collection< String > > m_refersTo; private Map< String, Collection< String > > m_unmutableRefersTo; /** * Maps page wikiname to a Set of referring pages. The Set must contain Strings. Non-existing pages (a reference exists, but * not a file for the page contents) may have an empty Set in m_referredBy. */ private Map< String, Set< String > > m_referredBy; private Map< String, Set< String > > m_unmutableReferredBy; private final boolean m_matchEnglishPlurals; private static final Logger LOG = LogManager.getLogger( DefaultReferenceManager.class); private static final String SERIALIZATION_FILE = "refmgr.ser"; private static final String SERIALIZATION_DIR = "refmgr-attr"; /** We use this also a generic serialization id */ private static final long serialVersionUID = 4L; /** * Builds a new ReferenceManager. * * @param engine The Engine to which this is managing references to. */ public DefaultReferenceManager( final Engine engine ) { m_refersTo = new ConcurrentHashMap<>(); m_referredBy = new ConcurrentHashMap<>(); m_engine = engine; m_matchEnglishPlurals = TextUtil.getBooleanProperty( engine.getWikiProperties(), Engine.PROP_MATCHPLURALS, false ); // // Create two maps that contain unmutable versions of the two basic maps. // m_unmutableReferredBy = Collections.unmodifiableMap( m_referredBy ); m_unmutableRefersTo = Collections.unmodifiableMap( m_refersTo ); } /** * Does a full reference update. Does not sync; assumes that you do it afterwards. */ private void updatePageReferences( final Page page ) throws ProviderException { final String content = m_engine.getManager( PageManager.class ).getPageText( page.getName(), PageProvider.LATEST_VERSION ); final Collection< String > links = scanWikiLinks( page, content ); final TreeSet< String > res = new TreeSet<>( links ); final List< Attachment > attachments = m_engine.getManager( AttachmentManager.class ).listAttachments( page ); for( final Attachment att : attachments ) { res.add( att.getName() ); } internalUpdateReferences( page.getName(), res ); } /** * Initializes the entire reference manager with the initial set of pages from the collection. * * @param pages A collection of all pages you want to be included in the reference count. * @since 2.2 * @throws ProviderException If reading of pages fails. */ @Override public void initialize( final Collection< Page > pages ) throws ProviderException { LOG.debug( "Initializing new ReferenceManager with {} initial pages.", pages.size() ); final StopWatch sw = new StopWatch(); sw.start(); LOG.info( "Starting cross reference scan of WikiPages" ); // First, try to serialize old data from disk. If that fails, we'll go and update the entire reference lists (which'll take time) try { // Unserialize things. The loop below cannot be combined with the other loop below, simply because // engine.getPage() has side effects such as loading initializing the user databases, which in turn want all // the pages to be read already... // // Yes, this is a kludge. We know. Will be fixed. final long saved = unserializeFromDisk(); for( final Page page : pages ) { unserializeAttrsFromDisk( page ); } // Now we must check if any of the pages have been changed while we were in the electronic la-la-land, // and update the references for them. for( final Page page : pages ) { if( !( page instanceof Attachment ) ) { // Refresh with the latest copy final Page wp = m_engine.getManager( PageManager.class ).getPage( page.getName() ); if( wp.getLastModified() == null ) { LOG.fatal( "Provider returns null lastModified. Please submit a bug report." ); } else if( wp.getLastModified().getTime() > saved ) { updatePageReferences( wp ); } } } } catch( final Exception e ) { LOG.info( "Unable to unserialize old refmgr information, rebuilding database: {}", e.getMessage() ); buildKeyLists( pages ); // Scan the existing pages from disk and update references in the manager. for( final Page page : pages ) { // We cannot build a reference list from the contents of attachments, so we skip them. if( !( page instanceof Attachment ) ) { updatePageReferences( page ); serializeAttrsToDisk( page ); } } serializeToDisk(); } sw.stop(); LOG.info( "Cross reference scan done in {}", sw ); WikiEventManager.addWikiEventListener( m_engine.getManager( PageManager.class ), this ); } /** * Reads the serialized data from the disk back to memory. Returns the date when the data was last written on disk */ @SuppressWarnings("unchecked") private synchronized long unserializeFromDisk() throws IOException, ClassNotFoundException { final long saved; final File f = new File( m_engine.getWorkDir(), SERIALIZATION_FILE ); try( final ObjectInputStream in = new ObjectInputStream( new BufferedInputStream( Files.newInputStream( f.toPath() ) ) ) ) { final StopWatch sw = new StopWatch(); sw.start(); final long ver = in.readLong(); if( ver != serialVersionUID ) { throw new IOException("File format has changed; I need to recalculate references."); } saved = in.readLong(); m_refersTo = ( Map< String, Collection< String > > ) in.readObject(); m_referredBy = ( Map< String, Set< String > > ) in.readObject(); m_unmutableReferredBy = Collections.unmodifiableMap( m_referredBy ); m_unmutableRefersTo = Collections.unmodifiableMap( m_refersTo ); sw.stop(); LOG.debug( "Read serialized data successfully in {}", sw ); } return saved; } /** * Serializes hashmaps to disk. The format is private, don't touch it. */ private synchronized void serializeToDisk() { final File f = new File( m_engine.getWorkDir(), SERIALIZATION_FILE ); try( final ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream( Files.newOutputStream( f.toPath() ) ) ) ) { final StopWatch sw = new StopWatch(); sw.start(); out.writeLong( serialVersionUID ); out.writeLong( System.currentTimeMillis() ); // Timestamp out.writeObject( m_refersTo ); out.writeObject( m_referredBy ); sw.stop(); LOG.debug( "serialization done - took {}", sw ); } catch( final IOException ioe ) { LOG.error( "Unable to serialize!", ioe ); } } private String getHashFileName( final String pageName ) { if( pageName == null ) { return null; } try { final MessageDigest digest = MessageDigest.getInstance( "MD5" ); final byte[] dig = digest.digest( pageName.getBytes( StandardCharsets.UTF_8 ) ); return TextUtil.toHexString( dig ) + ".cache"; } catch( final NoSuchAlgorithmException e ) { LOG.fatal( "What do you mean - no such algorithm?", e ); return null; } } /** * Reads the serialized data from the disk back to memory. Returns the date when the data was last written on disk */ private synchronized long unserializeAttrsFromDisk( final Page p ) throws IOException, ClassNotFoundException { long saved = 0L; // Find attribute cache, and check if it exists final String hashName = getHashFileName( p.getName() ); if( hashName != null ) { File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR ); f = new File( f, hashName ); if( !f.exists() ) { return 0L; } try( final ObjectInputStream in = new ObjectInputStream( new BufferedInputStream( Files.newInputStream( f.toPath() ) ) ) ) { final StopWatch sw = new StopWatch(); sw.start(); LOG.debug( "Deserializing attributes for {}", p.getName() ); final long ver = in.readLong(); if( ver != serialVersionUID ) { LOG.debug( "File format has changed; cannot deserialize." ); return 0L; } saved = in.readLong(); final String name = in.readUTF(); if( !name.equals( p.getName() ) ) { LOG.debug( "File name does not match ({}), skipping...", name ); return 0L; // Not here } final long entries = in.readLong(); for( int i = 0; i < entries; i++ ) { final String key = in.readUTF(); final Object value = in.readObject(); p.setAttribute( key, value ); LOG.debug( " attr: {}={}", key, value ); } sw.stop(); LOG.debug( "Read serialized data for {} successfully in {}", name, sw ); p.setHasMetadata(); } } return saved; } /** * Serializes hashmaps to disk. The format is private, don't touch it. */ private synchronized void serializeAttrsToDisk( final Page p ) { final StopWatch sw = new StopWatch(); sw.start(); final String hashName = getHashFileName( p.getName() ); if( hashName != null ) { File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR ); if( !f.exists() ) { f.mkdirs(); } // Create a digest for the name f = new File( f, hashName ); try( final ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream( Files.newOutputStream( f.toPath() ) ) ) ) { // new Set to avoid concurrency issues final Set< Map.Entry < String, Object > > entries = new HashSet<>( p.getAttributes().entrySet() ); if(entries.isEmpty()) { // Nothing to serialize, therefore we will just simply remove the serialization file so that the // next time we boot, we don't deserialize old data. f.delete(); return; } out.writeLong( serialVersionUID ); out.writeLong( System.currentTimeMillis() ); // Timestamp out.writeUTF( p.getName() ); out.writeLong( entries.size() ); for( final Map.Entry< String, Object > e : entries ) { if( e.getValue() instanceof Serializable ) { out.writeUTF( e.getKey() ); out.writeObject( e.getValue() ); } } } catch( final IOException e ) { LOG.error( "Unable to serialize!", e ); } finally { sw.stop(); LOG.debug( "serialization for {} done - took {}", p.getName(), sw ); } } } /** * After the page has been saved, updates the reference lists. * * @param context {@inheritDoc} * @param content {@inheritDoc} */ @Override public void postSave( final Context context, final String content ) { final Page page = context.getPage(); updateReferences( page.getName(), scanWikiLinks( page, content ) ); serializeAttrsToDisk( page ); } /** * Reads a WikiPageful of data from a String and returns all links internal to this Wiki in a Collection. * * @param page The WikiPage to scan * @param pagedata The page contents * @return a Collection of Strings */ @Override public Collection< String > scanWikiLinks( final Page page, final String pagedata ) { final LinkCollector localCollector = new LinkCollector(); m_engine.getManager( RenderingManager.class ).textToHTML( Wiki.context().create( m_engine, page ), pagedata, localCollector, null, localCollector, false, true ); return localCollector.getLinks(); } /** * Updates the m_referedTo and m_referredBy hashmaps when a page has been deleted. * <P> * Within the m_refersTo map the pagename is a key. The whole key-value-set has to be removed to keep the map clean. * Within the m_referredBy map the name is stored as a value. Since a key can have more than one value we have to * delete just the key-value-pair referring page:deleted page. * * @param page Name of the page to remove from the maps. */ @Override public void pageRemoved( final Page page ) { pageRemoved( page.getName() ); } private void pageRemoved( final String pageName ) { final Collection< String > refTo = m_refersTo.get( pageName ); if( refTo != null ) { for( final String referredPageName : refTo ) { final Set< String > refBy = m_referredBy.get( referredPageName ); if( refBy == null ) { throw new InternalWikiException( "Refmgr out of sync: page " + pageName + " refers to " + referredPageName + ", which has null referrers." ); } refBy.remove( pageName ); m_referredBy.remove( referredPageName ); // We won't put it back again if it becomes empty and does not exist. It will be added // later on anyway, if it becomes referenced again. if( !( refBy.isEmpty() && !m_engine.getManager( PageManager.class ).wikiPageExists( referredPageName ) ) ) { m_referredBy.put( referredPageName, refBy ); } } LOG.debug( "Removing from m_refersTo HashMap key:value {}:{}", pageName, m_refersTo.get( pageName ) ); m_refersTo.remove( pageName ); } final Set< String > refBy = m_referredBy.get( pageName ); if( refBy == null || refBy.isEmpty() ) { m_referredBy.remove( pageName ); } // Remove any traces from the disk, too serializeToDisk(); final String hashName = getHashFileName( pageName ); if( hashName != null ) { File f = new File( m_engine.getWorkDir(), SERIALIZATION_DIR ); f = new File( f, getHashFileName( pageName ) ); if( f.exists() ) { f.delete(); } } } /** * Updates all references for the given page. * * @param page wiki page for which references should be updated */ @Override public void updateReferences( final Page page ) { final String pageData = m_engine.getManager( PageManager.class ).getPureText( page.getName(), WikiProvider.LATEST_VERSION ); updateReferences( page.getName(), scanWikiLinks( page, pageData ) ); } /** * Updates the referred pages of a new or edited WikiPage. If a refersTo entry for this page already exists, it is removed * and a new one is built from scratch. Also calls updateReferredBy() for each referenced page. * <P> * This is the method to call when a new page has been created, and we want to a) set up its references and b) notify the * referred pages of the references. Use this method during run-time. * * @param page Name of the page to update. * @param references A Collection of Strings, each one pointing to a page this page references. */ @Override public void updateReferences( final String page, final Collection< String > references ) { internalUpdateReferences( page, references ); serializeToDisk(); } /** * Updates the referred pages of a new or edited WikiPage. If a refersTo entry for this page already exists, it is * removed and a new one is built from scratch. Also calls updateReferredBy() for each referenced page. * <p> * This method does not synchronize the database to disk. * * @param page Name of the page to update. * @param references A Collection of Strings, each one pointing to a page this page references. */ private void internalUpdateReferences( String page, final Collection< String > references) { page = getFinalPageName( page ); // Create a new entry in m_refersTo. final Collection< String > oldRefTo = m_refersTo.get( page ); m_refersTo.remove( page ); final TreeSet< String > cleanedRefs = references.stream().map(this::getFinalPageName).collect(Collectors.toCollection(TreeSet::new)); m_refersTo.put( page, cleanedRefs ); // We know the page exists, since it's making references somewhere. If an entry for it didn't exist previously // in m_referredBy, make sure one is added now. if( !m_referredBy.containsKey( page ) ) { m_referredBy.put( page, new TreeSet<>() ); } // Get all pages that used to be referred to by 'page' and remove that reference. (We don't want to try to figure out // which particular references were removed...) cleanReferredBy( page, oldRefTo); // Notify all referred pages of their referinesshoodicity. for( final String referredPageName : cleanedRefs ) { updateReferredBy( getFinalPageName( referredPageName ), page ); } } /** * Returns the refers-to list. For debugging. * * @return The refers-to list. */ protected Map< String, Collection< String > > getRefersTo() { return m_refersTo; } /** * Returns the referred-by list. For debugging. * * @return Referred-by lists. */ protected Map< String, Set< String > > getReferredBy() { return m_referredBy; } /** * Cleans the 'referred by' list, removing references by 'referrer' to any other page. Called after 'referrer' is removed. * * Two ways to go about this. One is to look up all pages previously referred by referrer and remove referrer * from their lists, and let the update put them back in (except possibly removed ones). * * The other is to get the old referred-to list, compare to the new, and tell the ones missing in the latter to remove referrer from * their list. * * We'll just try the first for now. Need to come back and optimize this a bit. */ private void cleanReferredBy( final String referrer, final Collection< String > oldReferred ) { if( oldReferred == null ) { return; } for( final String referredPage : oldReferred ) { final Set< String > oldRefBy = m_referredBy.get( referredPage ); if( oldRefBy != null ) { oldRefBy.remove( referrer ); } // If the page is referred to by no one AND it doesn't even exist, we might just as well forget about this // entry. It will be added again elsewhere if new references appear. if( ( oldRefBy == null || oldRefBy.isEmpty() ) && !m_engine.getManager( PageManager.class ).wikiPageExists( referredPage ) ) { m_referredBy.remove( referredPage ); } } } /** * When initially building a ReferenceManager from scratch, call this method BEFORE calling updateReferences() with * a full list of existing page names. It builds the refersTo and referredBy key lists, thus enabling updateReferences() * to function correctly. * <P> * This method should NEVER be called after initialization. It clears all mappings from the reference tables. * * @param pages a Collection containing WikiPage objects. */ private void buildKeyLists( final Collection< Page > pages ) { m_refersTo.clear(); m_referredBy.clear(); if( pages == null ) { return; } try { for( final Page page : pages ) { // We add a non-null entry to referredBy to indicate the referred page exists m_referredBy.put( page.getName(), new TreeSet<>() ); // Just add a key to refersTo; the keys need to be in sync with referredBy. m_refersTo.put( page.getName(), new TreeSet<>() ); } } catch( final ClassCastException e ) { LOG.fatal( "Invalid collection entry in ReferenceManager.buildKeyLists().", e ); } } /** * Marks the page as referred to by the referrer. If the page does not exist previously, nothing is done. (This means * that some page, somewhere, has a link to a page that does not exist.) */ private void updateReferredBy( final String page, final String referrer ) { // We're not really interested in first level self-references. /* if( page.equals( referrer ) ) { return; } */ // Neither are we interested if plural forms refer to each other. if( m_matchEnglishPlurals ) { final String p2 = page.endsWith( "s" ) ? page.substring( 0, page.length() - 1 ) : page + "s"; if( referrer.equals( p2 ) ) { return; } } // Even if 'page' has not been created yet, it can still be referenced. This requires we don't use m_referredBy // keys when looking up missing pages, of course. final Set< String > referrers = m_referredBy.computeIfAbsent( page, k -> new TreeSet<>() ); referrers.add( referrer ); } /** * Clears the references to a certain page, so it's no longer in the map. * * @param pagename Name of the page to clear references for. */ @Override public void clearPageEntries( String pagename ) { pagename = getFinalPageName( pagename ); // Remove this item from the referredBy list of any page which this item refers to. final Collection< String > c = m_refersTo.get( pagename ); if( c != null ) { for( final String key : c ) { final Collection< ? > dref = m_referredBy.get( key ); dref.remove( pagename ); } } // Finally, remove direct references. m_referredBy.remove( pagename ); m_refersTo.remove( pagename ); } /** * Finds all unreferenced pages. This requires a linear scan through m_referredBy to locate keys with null or empty values. * * @return The Collection of Strings */ @Override public Collection< String > findUnreferenced() { final ArrayList< String > unref = new ArrayList<>(); for( final String key : m_referredBy.keySet() ) { final Set< ? > refs = getReferenceList( m_referredBy, key ); if( refs == null || refs.isEmpty() ) { unref.add( key ); } } return unref; } /** * Finds all references to non-existant pages. This requires a linear scan through m_refersTo values; each value * must have a corresponding key entry in the reference Maps, otherwise such a page has never been created. * <P> * Returns a Collection containing Strings of unreferenced page names. Each non-existant page name is shown only * once - we don't return information on who referred to it. * * @return A Collection of Strings */ @Override public Collection< String > findUncreated() { final TreeSet< String > uncreated; // Go through m_refersTo values and check that m_refersTo has the corresponding keys. // We want to reread the code to make sure our HashMaps are in sync... final Collection< Collection< String > > allReferences = m_refersTo.values(); uncreated = allReferences.stream().filter(Objects::nonNull).flatMap(Collection::stream).filter(aReference -> !m_engine.getManager(PageManager.class).wikiPageExists(aReference)).collect(Collectors.toCollection(TreeSet::new)); return uncreated; } /** * Searches for the given page in the given Map, and returns the set of references. This method also takes care of * English plural matching. * * @param coll The Map to search in * @param pagename The name to find. * @return The references list. */ private < T > Set< T > getReferenceList( final Map< String, Set< T > > coll, final String pagename ) { Set< T > refs = coll.get( pagename ); if( m_matchEnglishPlurals ) { // We'll add also matches from the "other" page. final Set< T > refs2; if( pagename.endsWith( "s" ) ) { refs2 = coll.get( pagename.substring( 0, pagename.length() - 1 ) ); } else { refs2 = coll.get( pagename + "s" ); } if( refs2 != null ) { if( refs != null ) { refs.addAll( refs2 ); } else { refs = refs2; } } } return refs; } /** * Find all pages that refer to this page. Returns null if the page does not exist or is not referenced at all, * otherwise returns a collection containing page names (String) that refer to this one. * <p> * @param pagename The page to find referrers for. * @return A Set of Strings. May return null, if the page does not exist, or if it has no references. */ @Override public Set< String > findReferrers( final String pagename ) { final Set< String > refs = getReferenceList( m_referredBy, pagename ); if( refs == null || refs.isEmpty() ) { return null; } return refs; } /** * Returns all pages that refer to this page. Note that this method returns an unmodifiable Map, which may be abruptly changed. * So any access to any iterator may result in a ConcurrentModificationException. * <p> * The advantages of using this method over findReferrers() is that it is very fast, as it does not create a new object. * The disadvantages are that it does not do any mapping between plural names, and you may end up getting a * ConcurrentModificationException. * * @param pageName Page name to query. * @return A Set of Strings containing the names of all the pages that refer to this page. May return null, if the page does * not exist or has not been indexed yet. * @since 2.2.33 */ @Override public Set< String > findReferredBy( final String pageName ) { return m_unmutableReferredBy.get( getFinalPageName(pageName) ); } /** * Returns all pages that this page refers to. You can use this as a quick way of getting the links from a page, but note * that it does not link any InterWiki, image, or external links. It does contain attachments, though. * <p> * The Collection returned is unmutable, so you cannot change it. It does reflect the current status and thus is a live * object. So, if you are using any kind of an iterator on it, be prepared for ConcurrentModificationExceptions. * <p> * The returned value is a Collection, because a page may refer to another page multiple times. * * @param pageName Page name to query * @return A Collection of Strings containing the names of the pages that this page refers to. May return null, if the page * does not exist or has not been indexed yet. * @since 2.2.33 */ @Override public Collection< String > findRefersTo( final String pageName ) { return m_unmutableRefersTo.get( getFinalPageName( pageName ) ); } /** * This 'deepHashCode' can be used to determine if there were any modifications made to the underlying to and by maps of the * ReferenceManager. The maps of the ReferenceManager are not synchronized, so someone could add/remove entries in them while the * hashCode is being computed. * * This method traps and retries if a concurrent modification occurs. * * @return Sum of the hashCodes for the to and by maps of the ReferenceManager * @since 2.3.24 */ // // TODO: It is unnecessary to calculate the hashcode; it should be calculated only when the hashmaps are changed. This is slow. // public int deepHashCode() { boolean failed = true; int signature = 0; while( failed ) { signature = 0; try { signature ^= m_referredBy.hashCode(); signature ^= m_refersTo.hashCode(); failed = false; } catch ( final ConcurrentModificationException e) { Thread.yield(); } } return signature; } /** * Returns a list of all pages that the ReferenceManager knows about. This should be roughly equivalent to * PageManager.getAllPages(), but without the potential disk access overhead. Note that this method is not guaranteed * to return a Set of really all pages (especially during startup), but it is very fast. * * @return A Set of all defined page names that ReferenceManager knows about. * @since 2.3.24 */ @Override public Set< String > findCreated() { return new HashSet<>( m_refersTo.keySet() ); } private String getFinalPageName( final String orig ) { try { final String s = m_engine.getFinalPageName( orig ); return s != null ? s : orig; } catch( final ProviderException e ) { LOG.error( "Error while trying to fetch a page name; trying to cope with the situation.", e ); return orig; } } /** * {@inheritDoc} */ @Override public void actionPerformed( final WikiEvent event ) { if( event instanceof WikiPageEvent && event.getType() == WikiPageEvent.PAGE_DELETED ) { final String pageName = ( ( WikiPageEvent ) event ).getPageName(); if( pageName != null ) { pageRemoved( pageName ); } } } }
apache/harmony
36,703
classlib/modules/sql/src/main/java/javax/sql/RowSet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.sql; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.Ref; import java.sql.Time; import java.sql.Timestamp; import java.util.Map; import java.io.InputStream; import java.io.Reader; import java.util.Calendar; import java.math.BigDecimal; /** * An interface which provides means to access data which * persists on a database. It extends the functionality of * {@link java.sql.ResultSet ResultSet} into a form that it can be used as a * JavaBean component, suited for a visual programming environment. * <p> * {@code RowSet} provides getters and setters for properties relating to the * general database environment together with the getters and setters for * distinct data values which constitute the row set. The {@code RowSet} class * supports JavaBean events so that other components in an application can be * informed when changes happen such as changes in data values. * <p> * {@code RowSet} is a facility implemented on top of the remainder of the JDBC * API. It may be <i>connected</i>, maintaining a connection to the database * throughout its lifecycle. The changes made on a <i>disconnected</i> {@code * RowSet} on the other hand can be persisted only establishing a new connection * with the database each time. * <p> * Disconnected {@code RowSets} make use of {@code RowSetReaders} to populate * the {@code RowSet} with data, possibly from a non-relational database source. * They may also use {@code RowSetWriters} to send data back to the underlying * data store. There is considerable freedom in the way that {@code * RowSetReaders} and {@code RowSetWriters} may be implemented to retrieve and * store data. * * @see RowSetReader * @see RowSetWriter */ public interface RowSet extends ResultSet { /** * Registers the supplied {@link RowSetListener} with this {@code RowSet}. * Once registered, the {@link RowSetListener} is notified of events * generated by the {@code RowSet}. * * @param theListener * an object which implements the {@code rowSetListener} * interface. */ public void addRowSetListener(RowSetListener theListener); /** * Clears the parameters previously set for this {@code RowSet}. * <p> * The {@code RowSet} object retains its value until either a new value for * a parameter is set or its value is actively reset. {@code * clearParameters} provides a facility to clear the values for all * parameters with one method call. * * @throws SQLException * if a problem occurs accessing the database. */ public void clearParameters() throws SQLException; /** * Fetches data for this {@code RowSet} from the database. If successful, * any existing data for the {@code RowSet} is discarded and its metadata is * overwritten. * <p> * Data is retrieved connecting to the database and executing an * according SQL statement. This requires some or all of the following * properties to be set: URL, database name, user name, password, * transaction isolation, type map; plus some or all of the properties: * command, read only, maximum field size, maximum rows, escape processing, * and query timeout. * <p> * The {@code RowSet} may use a {@code RowSetReader} to access the database * it will then invoke the {@link RowSetReader#readData} method on the * reader to fetch the data. When the new data is fetched all the listeners * are notified to take appropriate measures. * * @throws SQLException * if a problem occurs accessing the database or if the * properties needed to access the database have not been set. * @see RowSetMetaData * @see RowSetReader */ public void execute() throws SQLException; /** * Gets the {@code RowSet}'s command property. * * @return a string containing the {@code RowSet}'s command property. A * command is a SQL statement which is executed to fetch required * data into the {@code RowSet}. */ public String getCommand(); /** * Gets the ODBC Data Source Name property associated with this {@code * RowSet}. The database name can be used to find a {@link DataSource} * which has been registered with a naming service - the {@link DataSource} * can then be used to create a connection to the database. * * @return the name of the database. */ public String getDataSourceName(); /** * Reports if escape processing is enabled for this {@code RowSet}. If * escape processing is on, the driver performs a substitution of the escape * syntax with the applicable code before sending an SQL command to the * database. The default value for escape processing is {@code true}. * * @return {@code true} if escape processing is enabled, {@code * false} otherwise. * @throws SQLException * if a problem occurs accessing the database. */ public boolean getEscapeProcessing() throws SQLException; /** * Gets the maximum number of bytes that can be returned for column values * which are of type {@code BINARY}, {@code VARBINARY}, {@code * LONGVARBINARYBINARY}, {@code CHAR}, {@code VARCHAR}, or {@code * LONGVARCHAR}. Excess data is silently discarded if the number is * exceeded. * * @return the current maximum size in bytes. 0 implies no size limit. * @throws SQLException * if a problem occurs accessing the database. */ public int getMaxFieldSize() throws SQLException; /** * Gets the maximum number of rows for this {@code RowSet}. Excess rows are * discarded silently if the limit is exceeded. * * @return the previous maximum number of rows. 0 implies no row limit. * @throws SQLException * if a problem occurs accessing the database. */ public int getMaxRows() throws SQLException; /** * Gets the value of the password property for this {@code RowSet}. This * property is used when a connection to the database is established. * Therefore it should be set prior to invoking the {@link #execute} method. * * @return the value of the password property. */ public String getPassword(); /** * Gets the timeout for the driver when a query operation is executed. If a * query takes longer than the timeout then a {@code SQLException} is * thrown. * * @return the timeout value in seconds. * @throws SQLException * if an error occurs accessing the database. */ public int getQueryTimeout() throws SQLException; /** * Gets the transaction isolation level property set for this * {@code RowSet}. The transaction isolation level defines the * policy implemented on the database for maintaining the data * values consistent. * * @return the current transaction isolation level. Must be one of: * <ul> * <li>{@code Connection.TRANSACTION_READ_UNCOMMITTED}</li> * <li>{@code Connection.TRANSACTION_READ_COMMITTED}</li> * <li>{@code Connection.TRANSACTION_REPEATABLE_READ}</li> * <li>{@code Connection.TRANSACTION_SERIALIZABLE}</li> * </ul> * @see java.sql.Connection */ public int getTransactionIsolation(); /** * Gets the custom mapping of SQL User-Defined Types (UDTs) and Java classes * for this {@code RowSet}, if applicable. * * @return the custom mappings of SQL types to Java classes. * @throws SQLException * if an error occurs accessing the database. */ public Map<String, Class<?>> getTypeMap() throws SQLException; /** * Gets the URL property value for this {@code RowSet}. If there is no * {@code DataSource} object specified, the {@code RowSet} uses the URL to * establish a connection to the database. The default value for the URL is * {@code null}. * * @return a String holding the value of the URL property. * @throws SQLException * if an error occurs accessing the database. */ public String getUrl() throws SQLException; /** * Gets the value of the {@code username} property for this {@code RowSet}. * The {@code username} is used when establishing a connection to the * database and should be set before the {@code execute} method is invoked. * * @return a {@code String} holding the value of the {@code username} * property. */ public String getUsername(); /** * Indicates if this {@code RowSet} is read-only. * * @return {@code true} if this {@code RowSet} is read-only, {@code false} * if it is updatable. */ public boolean isReadOnly(); /** * Removes a specified {@link RowSetListener} object from the set of * listeners which will be notified of events by this {@code RowSet}. * * @param theListener * the {@link RowSetListener} to remove from the set of listeners * for this {@code RowSet}. */ public void removeRowSetListener(RowSetListener theListener); /** * Sets the specified {@code ARRAY} parameter in the {@code RowSet} command * with the supplied {@code java.sql.Array} value. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theArray * the {@code Array} data value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setArray(int parameterIndex, Array theArray) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the ASCII data in the supplied {@code java.io.InputStream} value. * Data is read from the {@code InputStream} until end-of-file is reached. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theInputStream * the ASCII data value to which the parameter is set. * @param length * the length of the data in bytes. * @throws SQLException * if an error occurs accessing the database. */ public void setAsciiStream(int parameterIndex, InputStream theInputStream, int length) throws SQLException; /** * Sets the value of the specified SQL {@code NUMERIC} parameter in the * {@code RowSet} command with the data in the supplied {@code * java.math.BigDecimal} value. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theBigDecimal * the big decimal value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setBigDecimal(int parameterIndex, BigDecimal theBigDecimal) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to the binary data in the supplied input stream. Data is read from the * input stream until end-of-file is reached. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theInputStream * the binary data stream to which the parameter is set. * @param length * the length of the data in bytes. * @throws SQLException * if an error occurs accessing the database. */ public void setBinaryStream(int parameterIndex, InputStream theInputStream, int length) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to the supplied {@code Blob} value. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theBlob * the {@code Blob} value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setBlob(int parameterIndex, Blob theBlob) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to the supplied boolean. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theBoolean * the {@code boolean} value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setBoolean(int parameterIndex, boolean theBoolean) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to the supplied byte value. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theByte * the {@code byte} value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setByte(int parameterIndex, byte theByte) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to the supplied byte array value. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theByteArray * the {@code Array} of {@code bytes} to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setBytes(int parameterIndex, byte[] theByteArray) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to the sequence of Unicode characters carried by the supplied {@code * java.io.Reader}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theReader * the {@code Reader} which contains the Unicode data to set the * parameter. * @param length * the length of the data in the {@code Reader} in characters. * @throws SQLException * if an error occurs accessing the database. */ public void setCharacterStream(int parameterIndex, Reader theReader, int length) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the value of a supplied {@code java.sql.Clob}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theClob * the {@code Clob} value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setClob(int parameterIndex, Clob theClob) throws SQLException; /** * Sets the Command property for this {@code RowSet} - the command is an SQL * query which runs when the {@code execute} method is invoked. This * property is optional for databases that do not support commands. * * @param cmd * the SQL query. Can be {@code null}. * @throws SQLException * if an error occurs accessing the database. */ public void setCommand(String cmd) throws SQLException; /** * Sets the concurrency property of this {@code RowSet}. The default value * is {@code ResultSet.CONCUR_READ_ONLY}. * * @param concurrency * the concurrency value. One of: * <ul> * <li>{@code ResultSet.CONCUR_READ_ONLY}</li> * <li>{@code ResultSet.CONCUR_UPDATABLE}</li> * </ul> * @throws SQLException * if an error occurs accessing the database. * @see java.sql.ResultSet */ public void setConcurrency(int concurrency) throws SQLException; /** * Sets the database name property for the {@code RowSet}. * <p> * The database name can be used to find a {@link DataSource} which has been * registered with a naming service - the {@link DataSource} can then be * used to create a connection to the database. * * @param name * the database name. * @throws SQLException * if an error occurs accessing the database. */ public void setDataSourceName(String name) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the value of a supplied {@code java.sql.Date}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theDate * the date value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setDate(int parameterIndex, Date theDate) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the value of a supplied {@code java.sql.Date}, where the conversion * of the date to an SQL {@code DATE} value is calculated using a supplied * {@code Calendar}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theDate * the date to which the parameter is set. * @param theCalendar * the {@code Calendar} to use in converting the Date to an SQL * {@code DATE} value. * @throws SQLException * if an error occurs accessing the database. */ public void setDate(int parameterIndex, Date theDate, Calendar theCalendar) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the supplied {@code double}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theDouble * the {@code double} value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setDouble(int parameterIndex, double theDouble) throws SQLException; /** * Sets the escape processing status for this {@code RowSet}. If escape * processing is on, the driver performs a substitution of the escape syntax * with the applicable code before sending an SQL command to the database. * The default value for escape processing is {@code true}. * * @param enable * {@code true} to enable escape processing, {@code false} to * turn it off. * @throws SQLException * if an error occurs accessing the database. */ public void setEscapeProcessing(boolean enable) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the supplied {@code float}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theFloat * the {@code float} value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setFloat(int parameterIndex, float theFloat) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the supplied {@code integer}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theInteger * the {@code integer} value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setInt(int parameterIndex, int theInteger) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * with the supplied {@code long}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theLong * the {@code long} value value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setLong(int parameterIndex, long theLong) throws SQLException; /** * Sets the maximum number of bytes which can be returned for a column value * where the column type is one of {@code BINARY}, {@code VARBINARY}, * {@code LONGVARBINARYBINARY}, {@code CHAR}, {@code VARCHAR}, or {@code * LONGVARCHAR}. Data which exceeds this limit is silently discarded. For * portability, a value greater than 256 is recommended. * * @param max * the maximum size of the returned column value in bytes. 0 * implies no size limit. * @throws SQLException * if an error occurs accessing the database. */ public void setMaxFieldSize(int max) throws SQLException; /** * Sets the maximum number of rows which can be held by the {@code RowSet}. * Any additional rows are silently discarded. * * @param max * the maximum number of rows which can be held in the {@code * RowSet}. 0 means no limit. * @throws SQLException * if an error occurs accessing the database. */ public void setMaxRows(int max) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to SQL {@code NULL}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param sqlType * the type of the parameter, as defined by {@code * java.sql.Types}. * @throws SQLException * if an error occurs accessing the database. */ public void setNull(int parameterIndex, int sqlType) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to SQL {@code NULL}. This form of the {@code setNull} method should be * used for User Defined Types and {@code REF} parameters. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param sqlType * the type of the parameter, as defined by {@code * java.sql.Types}. * @param typeName * the fully qualified name of an SQL user defined type or the * name of the SQL structured type referenced by a {@code REF} * type. Ignored if the sqlType is not a UDT or REF type. * @throws SQLException * if an error occurs accessing the database. */ public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied Java object. * <p> * The JDBC specification provides a standard mapping for Java objects to * SQL data types. Database specific types can be mapped by JDBC driver * specific Java types. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theObject * the Java object containing the data value to which the * parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setObject(int parameterIndex, Object theObject) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied Java object. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theObject * the Java object containing the data value. * @param targetSqlType * the SQL type to send to the database, as defined in {@code * java.sql.Types}. * @throws SQLException * if an error occurs accessing the database. */ public void setObject(int parameterIndex, Object theObject, int targetSqlType) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied Java object. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theObject * the Java object containing the data value. * @param targetSqlType * the SQL type to send to the database, as defined in {@code * java.sql.Types}. * @param scale * the number of digits after the decimal point, for {@code * java.sql.Types.DECIMAL} and {@code java.sql.Types.NUMERIC} * types. Ignored for all other types. * @throws SQLException * if an error occurs accessing the database. */ public void setObject(int parameterIndex, Object theObject, int targetSqlType, int scale) throws SQLException; /** * Sets the database Password for this {@code RowSet}. This property is used * when a connection to the database is established. Therefore it should be * set prior to invoking the {@link #execute} method. * * @param password * a {@code String} holding the password. * @throws SQLException * if an error occurs accessing the database. */ public void setPassword(String password) throws SQLException; /** * Gets the timeout for the driver when a query operation is executed. If a * query takes longer than the timeout, a {@code SQLException} is thrown. * * @param seconds * the number of seconds for the timeout. * @throws SQLException * if an error occurs accessing the database. */ public void setQueryTimeout(int seconds) throws SQLException; /** * Sets whether the {@code RowSet} is read-only or updatable. * * @param readOnly * {@code true} to set the {@code RowSet} to read-only state, * {@code false} to allow updates. * @throws SQLException * if an error occurs accessing the database. */ public void setReadOnly(boolean readOnly) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied {@code java.sql.Ref}. This is sent to the database as an * SQL {@code REF} value. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theRef * the value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. * @see java.sql.Ref */ public void setRef(int parameterIndex, Ref theRef) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied {@code short integer}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theShort * the value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setShort(int parameterIndex, short theShort) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied {@code String}. The string is placed into the database as a * {@code VARCHAR} or {@code LONGVARCHAR} SQL value, depending on the * database limits for the length of {@code VARCHAR} values. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theString * the value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. */ public void setString(int parameterIndex, String theString) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied {@code java.sql.Time}, converting it to an SQL {@code TIME} * value using the system default {@code Calendar}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theTime * the value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. * @see java.util.Calendar * @see java.sql.Time */ public void setTime(int parameterIndex, Time theTime) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied {@code java.sql.Time}, converting it to an SQL {@code TIME} * value using a supplied {@code Calendar}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theTime * the value to which the parameter is set. * @param theCalendar * the {@code Calendar} to use in the conversion operation. * @throws SQLException * if an error occurs accessing the database. * @see java.util.Calendar * @see java.sql.Time */ public void setTime(int parameterIndex, Time theTime, Calendar theCalendar) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied {@code java.sql.Timestamp}, converting it to an SQL {@code * TIMESTAMP} value using the system default {@code Calendar}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theTimestamp * the value to which the parameter is set. * @throws SQLException * if an error occurs accessing the database. * @see java.util.Calendar * @see java.sql.Timestamp */ public void setTimestamp(int parameterIndex, Timestamp theTimestamp) throws SQLException; /** * Sets the value of the specified parameter in the {@code RowSet} command * to a supplied {@code java.sql.Timestamp}, converting it to an SQL {@code * TIMESTAMP} value using a supplied {@code Calendar}. * * @param parameterIndex * the index of the parameter to set; the first parameter's index * is 1. * @param theTimestamp * the value to which the parameter is set. * @param theCalendar * the {@code Calendar} to use in the conversion operation * @throws SQLException * if an error occurs accessing the database. * @see java.util.Calendar * @see java.sql.Timestamp */ public void setTimestamp(int parameterIndex, Timestamp theTimestamp, Calendar theCalendar) throws SQLException; /** * Sets the target instance's transaction isolation level to one of a * discrete set of possible values. The transaction isolation level defines * the policy implemented on the database for maintaining the data values * consistent. * <p> * Keep in mind that setting a transaction isolation level has no effect * unless your driver and DBMS support it. * * @param level * the transaction isolation level. One of: * <ul> * <li>{@code Connection.TRANSACTION_READ_UNCOMMITTED}</li> * <li>{@code Connection.TRANSACTION_READ_COMMITTED}</li> * <li>{@code Connection.TRANSACTION_REPEATABLE_READ}</li> * <li>{@code Connection.TRANSACTION_SERIALIZABLE}</li> * </ul> * @throws SQLException * if an error occurs accessing the database. * @see java.sql.Connection */ public void setTransactionIsolation(int level) throws SQLException; /** * Sets the type of this {@code RowSet}. By default, the type is * non-scrollable. * * @param type * the type for the {@code RowSet}. One of: * <ul> * <li>{@code ResultSet.TYPE_FORWARD_ONLY}</li> * <li>{@code ResultSet.TYPE_SCROLL_INSENSITIVE}</li> * <li>{@code ResultSet.TYPE_SCROLL_SENSITIVE}</li> * </ul> * @throws SQLException * if an error occurs accessing the database. */ public void setType(int type) throws SQLException; /** * Sets the mapping of SQL User Defined Types (UDTs) to Java classes. The * Java classes must all implement the {@link java.sql.SQLData SQLData} * interface. * * @param theTypeMap * the names of SQL UDTs and the Java classes to which they are * mapped. * @throws SQLException * if an error occurs accessing the database. */ public void setTypeMap(Map<String, Class<?>> theTypeMap) throws SQLException; /** * Sets the URL used by this {@code RowSet} to access the database via a * {@code DriverManager}. The URL is optional - an alternative is to use a * database name to create a connection. * * @param theURL * the URL for the database. Can be {@code null}. * @throws SQLException * if an error occurs accessing the database. */ public void setUrl(String theURL) throws SQLException; /** * Sets the {@code Username} property for the {@code RowSet}, used to * authenticate a connection to the database. * * @param theUsername * the new user name for this row set. * @throws SQLException * if an error occurs accessing the database. */ public void setUsername(String theUsername) throws SQLException; }
googleapis/sdk-platform-java
36,384
java-iam/proto-google-iam-v3/src/main/java/com/google/iam/v3/UpdatePolicyBindingRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/iam/v3/policy_bindings_service.proto // Protobuf Java Version: 3.25.8 package com.google.iam.v3; /** * * * <pre> * Request message for UpdatePolicyBinding method. * </pre> * * Protobuf type {@code google.iam.v3.UpdatePolicyBindingRequest} */ public final class UpdatePolicyBindingRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.iam.v3.UpdatePolicyBindingRequest) UpdatePolicyBindingRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdatePolicyBindingRequest.newBuilder() to construct. private UpdatePolicyBindingRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdatePolicyBindingRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdatePolicyBindingRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.iam.v3.PolicyBindingsServiceProto .internal_static_google_iam_v3_UpdatePolicyBindingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.iam.v3.PolicyBindingsServiceProto .internal_static_google_iam_v3_UpdatePolicyBindingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.iam.v3.UpdatePolicyBindingRequest.class, com.google.iam.v3.UpdatePolicyBindingRequest.Builder.class); } private int bitField0_; public static final int POLICY_BINDING_FIELD_NUMBER = 1; private com.google.iam.v3.PolicyBinding policyBinding_; /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the policyBinding field is set. */ @java.lang.Override public boolean hasPolicyBinding() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The policyBinding. */ @java.lang.Override public com.google.iam.v3.PolicyBinding getPolicyBinding() { return policyBinding_ == null ? com.google.iam.v3.PolicyBinding.getDefaultInstance() : policyBinding_; } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.iam.v3.PolicyBindingOrBuilder getPolicyBindingOrBuilder() { return policyBinding_ == null ? com.google.iam.v3.PolicyBinding.getDefaultInstance() : policyBinding_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 2; private boolean validateOnly_ = false; /** * * * <pre> * Optional. If set, validate the request and preview the update, but do not * actually post it. * </pre> * * <code>bool validate_only = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } public static final int UPDATE_MASK_FIELD_NUMBER = 3; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getPolicyBinding()); } if (validateOnly_ != false) { output.writeBool(2, validateOnly_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getUpdateMask()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getPolicyBinding()); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(2, validateOnly_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getUpdateMask()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.iam.v3.UpdatePolicyBindingRequest)) { return super.equals(obj); } com.google.iam.v3.UpdatePolicyBindingRequest other = (com.google.iam.v3.UpdatePolicyBindingRequest) obj; if (hasPolicyBinding() != other.hasPolicyBinding()) return false; if (hasPolicyBinding()) { if (!getPolicyBinding().equals(other.getPolicyBinding())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasPolicyBinding()) { hash = (37 * hash) + POLICY_BINDING_FIELD_NUMBER; hash = (53 * hash) + getPolicyBinding().hashCode(); } hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.iam.v3.UpdatePolicyBindingRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.iam.v3.UpdatePolicyBindingRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for UpdatePolicyBinding method. * </pre> * * Protobuf type {@code google.iam.v3.UpdatePolicyBindingRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.iam.v3.UpdatePolicyBindingRequest) com.google.iam.v3.UpdatePolicyBindingRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.iam.v3.PolicyBindingsServiceProto .internal_static_google_iam_v3_UpdatePolicyBindingRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.iam.v3.PolicyBindingsServiceProto .internal_static_google_iam_v3_UpdatePolicyBindingRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.iam.v3.UpdatePolicyBindingRequest.class, com.google.iam.v3.UpdatePolicyBindingRequest.Builder.class); } // Construct using com.google.iam.v3.UpdatePolicyBindingRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getPolicyBindingFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; policyBinding_ = null; if (policyBindingBuilder_ != null) { policyBindingBuilder_.dispose(); policyBindingBuilder_ = null; } validateOnly_ = false; updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.iam.v3.PolicyBindingsServiceProto .internal_static_google_iam_v3_UpdatePolicyBindingRequest_descriptor; } @java.lang.Override public com.google.iam.v3.UpdatePolicyBindingRequest getDefaultInstanceForType() { return com.google.iam.v3.UpdatePolicyBindingRequest.getDefaultInstance(); } @java.lang.Override public com.google.iam.v3.UpdatePolicyBindingRequest build() { com.google.iam.v3.UpdatePolicyBindingRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.iam.v3.UpdatePolicyBindingRequest buildPartial() { com.google.iam.v3.UpdatePolicyBindingRequest result = new com.google.iam.v3.UpdatePolicyBindingRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.iam.v3.UpdatePolicyBindingRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.policyBinding_ = policyBindingBuilder_ == null ? policyBinding_ : policyBindingBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.validateOnly_ = validateOnly_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.iam.v3.UpdatePolicyBindingRequest) { return mergeFrom((com.google.iam.v3.UpdatePolicyBindingRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.iam.v3.UpdatePolicyBindingRequest other) { if (other == com.google.iam.v3.UpdatePolicyBindingRequest.getDefaultInstance()) return this; if (other.hasPolicyBinding()) { mergePolicyBinding(other.getPolicyBinding()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getPolicyBindingFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 16: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.iam.v3.PolicyBinding policyBinding_; private com.google.protobuf.SingleFieldBuilderV3< com.google.iam.v3.PolicyBinding, com.google.iam.v3.PolicyBinding.Builder, com.google.iam.v3.PolicyBindingOrBuilder> policyBindingBuilder_; /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the policyBinding field is set. */ public boolean hasPolicyBinding() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The policyBinding. */ public com.google.iam.v3.PolicyBinding getPolicyBinding() { if (policyBindingBuilder_ == null) { return policyBinding_ == null ? com.google.iam.v3.PolicyBinding.getDefaultInstance() : policyBinding_; } else { return policyBindingBuilder_.getMessage(); } } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setPolicyBinding(com.google.iam.v3.PolicyBinding value) { if (policyBindingBuilder_ == null) { if (value == null) { throw new NullPointerException(); } policyBinding_ = value; } else { policyBindingBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setPolicyBinding(com.google.iam.v3.PolicyBinding.Builder builderForValue) { if (policyBindingBuilder_ == null) { policyBinding_ = builderForValue.build(); } else { policyBindingBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergePolicyBinding(com.google.iam.v3.PolicyBinding value) { if (policyBindingBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && policyBinding_ != null && policyBinding_ != com.google.iam.v3.PolicyBinding.getDefaultInstance()) { getPolicyBindingBuilder().mergeFrom(value); } else { policyBinding_ = value; } } else { policyBindingBuilder_.mergeFrom(value); } if (policyBinding_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearPolicyBinding() { bitField0_ = (bitField0_ & ~0x00000001); policyBinding_ = null; if (policyBindingBuilder_ != null) { policyBindingBuilder_.dispose(); policyBindingBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.iam.v3.PolicyBinding.Builder getPolicyBindingBuilder() { bitField0_ |= 0x00000001; onChanged(); return getPolicyBindingFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.iam.v3.PolicyBindingOrBuilder getPolicyBindingOrBuilder() { if (policyBindingBuilder_ != null) { return policyBindingBuilder_.getMessageOrBuilder(); } else { return policyBinding_ == null ? com.google.iam.v3.PolicyBinding.getDefaultInstance() : policyBinding_; } } /** * * * <pre> * Required. The policy binding to update. * * The policy binding's `name` field is used to identify the policy binding to * update. * </pre> * * <code> * .google.iam.v3.PolicyBinding policy_binding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.iam.v3.PolicyBinding, com.google.iam.v3.PolicyBinding.Builder, com.google.iam.v3.PolicyBindingOrBuilder> getPolicyBindingFieldBuilder() { if (policyBindingBuilder_ == null) { policyBindingBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.iam.v3.PolicyBinding, com.google.iam.v3.PolicyBinding.Builder, com.google.iam.v3.PolicyBindingOrBuilder>( getPolicyBinding(), getParentForChildren(), isClean()); policyBinding_ = null; } return policyBindingBuilder_; } private boolean validateOnly_; /** * * * <pre> * Optional. If set, validate the request and preview the update, but do not * actually post it. * </pre> * * <code>bool validate_only = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * Optional. If set, validate the request and preview the update, but do not * actually post it. * </pre> * * <code>bool validate_only = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. If set, validate the request and preview the update, but do not * actually post it. * </pre> * * <code>bool validate_only = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000002); validateOnly_ = false; onChanged(); return this; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000004); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000004; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Optional. The list of fields to update * </pre> * * <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.iam.v3.UpdatePolicyBindingRequest) } // @@protoc_insertion_point(class_scope:google.iam.v3.UpdatePolicyBindingRequest) private static final com.google.iam.v3.UpdatePolicyBindingRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.iam.v3.UpdatePolicyBindingRequest(); } public static com.google.iam.v3.UpdatePolicyBindingRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdatePolicyBindingRequest> PARSER = new com.google.protobuf.AbstractParser<UpdatePolicyBindingRequest>() { @java.lang.Override public UpdatePolicyBindingRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UpdatePolicyBindingRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdatePolicyBindingRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.iam.v3.UpdatePolicyBindingRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/commons-math
36,652
commons-math-neuralnet/src/test/java/org/apache/commons/math4/neuralnet/twod/NeuronSquareMesh2DTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math4.neuralnet.twod; import java.util.Collection; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.stream.StreamSupport; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Test; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; import org.apache.commons.math4.neuralnet.FeatureInitializer; import org.apache.commons.math4.neuralnet.FeatureInitializerFactory; import org.apache.commons.math4.neuralnet.Network; import org.apache.commons.math4.neuralnet.Neuron; import org.apache.commons.math4.neuralnet.SquareNeighbourhood; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests for {@link NeuronSquareMesh2D} and {@link Network} functionality for * a two-dimensional network. */ public class NeuronSquareMesh2DTest { private final UniformRandomProvider rng = RandomSource.SPLIT_MIX_64.create(); private final FeatureInitializer init = FeatureInitializerFactory.uniform(rng, 0, 2); @Test public void testMinimalNetworkSize1() { final FeatureInitializer[] initArray = {init}; assertThrows(IllegalArgumentException.class, () -> new NeuronSquareMesh2D(1, false, 2, false, SquareNeighbourhood.VON_NEUMANN, initArray)); } @Test public void testMinimalNetworkSize2() { final FeatureInitializer[] initArray = {init}; assertThrows(IllegalArgumentException.class, () -> new NeuronSquareMesh2D(2, false, 0, false, SquareNeighbourhood.VON_NEUMANN, initArray)); } @Test public void testGetFeaturesSize() { final FeatureInitializer[] initArray = {init, init, init}; final Network net = new NeuronSquareMesh2D(2, false, 2, false, SquareNeighbourhood.VON_NEUMANN, initArray).getNetwork(); Assert.assertEquals(3, net.getFeaturesSize()); } @Test public void testAccessors() { final FeatureInitializer[] initArray = {init}; NeuronSquareMesh2D map; for (SquareNeighbourhood type : SquareNeighbourhood.values()) { map = new NeuronSquareMesh2D(4, false, 2, true, type, initArray); Assert.assertFalse(map.isWrappedRow()); Assert.assertTrue(map.isWrappedColumn()); Assert.assertEquals(type, map.getSquareNeighbourhood()); map = new NeuronSquareMesh2D(3, true, 4, false, type, initArray); Assert.assertTrue(map.isWrappedRow()); Assert.assertFalse(map.isWrappedColumn()); Assert.assertEquals(type, map.getSquareNeighbourhood()); } } /* * Test assumes that the network is * * 0-----1 * | | * | | * 2-----3 */ @Test public void test2x2Network() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(2, false, 2, false, SquareNeighbourhood.VON_NEUMANN, initArray).getNetwork(); Collection<Neuron> neighbours; // Neurons 0 and 3. for (long id : new long[] {0, 3 }) { neighbours = net.getNeighbours(net.getNeuron(id)); for (long nId : new long[] {1, 2 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(2, neighbours.size()); } // Neurons 1 and 2. for (long id : new long[] {1, 2 }) { neighbours = net.getNeighbours(net.getNeuron(id)); for (long nId : new long[] {0, 3 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(2, neighbours.size()); } } /* * Test assumes that the network is * * 0-----1 * | | * | | * 2-----3 */ @Test public void test2x2Network2() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(2, false, 2, false, SquareNeighbourhood.MOORE, initArray).getNetwork(); Collection<Neuron> neighbours; // All neurons for (long id : new long[] {0, 1, 2, 3 }) { neighbours = net.getNeighbours(net.getNeuron(id)); for (long nId : new long[] {0, 1, 2, 3 }) { if (id != nId) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } } } } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 */ @Test public void test3x2CylinderNetwork() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(2, false, 3, true, SquareNeighbourhood.VON_NEUMANN, initArray).getNetwork(); Collection<Neuron> neighbours; // Neuron 0. neighbours = net.getNeighbours(net.getNeuron(0)); for (long nId : new long[] {1, 2, 3 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 1. neighbours = net.getNeighbours(net.getNeuron(1)); for (long nId : new long[] {0, 2, 4 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 2. neighbours = net.getNeighbours(net.getNeuron(2)); for (long nId : new long[] {0, 1, 5 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 3. neighbours = net.getNeighbours(net.getNeuron(3)); for (long nId : new long[] {0, 4, 5 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 4. neighbours = net.getNeighbours(net.getNeuron(4)); for (long nId : new long[] {1, 3, 5 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 5. neighbours = net.getNeighbours(net.getNeuron(5)); for (long nId : new long[] {2, 3, 4 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 */ @Test public void test3x2CylinderNetwork2() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(2, false, 3, true, SquareNeighbourhood.MOORE, initArray).getNetwork(); Collection<Neuron> neighbours; // All neurons. for (long id : new long[] {0, 1, 2, 3, 4, 5 }) { neighbours = net.getNeighbours(net.getNeuron(id)); for (long nId : new long[] {0, 1, 2, 3, 4, 5 }) { if (id != nId) { Assert.assertTrue("id=" + id + " nId=" + nId, neighbours.contains(net.getNeuron(nId))); } } } } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 * | | | * | | | * 6-----7-----8 */ @Test public void test3x3TorusNetwork() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(3, true, 3, true, SquareNeighbourhood.VON_NEUMANN, initArray).getNetwork(); Collection<Neuron> neighbours; // Neuron 0. neighbours = net.getNeighbours(net.getNeuron(0)); for (long nId : new long[] {1, 2, 3, 6 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 1. neighbours = net.getNeighbours(net.getNeuron(1)); for (long nId : new long[] {0, 2, 4, 7 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 2. neighbours = net.getNeighbours(net.getNeuron(2)); for (long nId : new long[] {0, 1, 5, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 3. neighbours = net.getNeighbours(net.getNeuron(3)); for (long nId : new long[] {0, 4, 5, 6 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 4. neighbours = net.getNeighbours(net.getNeuron(4)); for (long nId : new long[] {1, 3, 5, 7 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 5. neighbours = net.getNeighbours(net.getNeuron(5)); for (long nId : new long[] {2, 3, 4, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 6. neighbours = net.getNeighbours(net.getNeuron(6)); for (long nId : new long[] {0, 3, 7, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 7. neighbours = net.getNeighbours(net.getNeuron(7)); for (long nId : new long[] {1, 4, 6, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // Neuron 8. neighbours = net.getNeighbours(net.getNeuron(8)); for (long nId : new long[] {2, 5, 6, 7 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 * | | | * | | | * 6-----7-----8 */ @Test public void test3x3TorusNetwork2() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(3, true, 3, true, SquareNeighbourhood.MOORE, initArray).getNetwork(); Collection<Neuron> neighbours; // All neurons. for (long id : new long[] {0, 1, 2, 3, 4, 5, 6, 7, 8 }) { neighbours = net.getNeighbours(net.getNeuron(id)); for (long nId : new long[] {0, 1, 2, 3, 4, 5, 6, 7, 8 }) { if (id != nId) { Assert.assertTrue("id=" + id + " nId=" + nId, neighbours.contains(net.getNeuron(nId))); } } } } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 * | | | * | | | * 6-----7-----8 */ @Test public void test3x3CylinderNetwork() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(3, false, 3, true, SquareNeighbourhood.MOORE, initArray).getNetwork(); Collection<Neuron> neighbours; // Neuron 0. neighbours = net.getNeighbours(net.getNeuron(0)); for (long nId : new long[] {1, 2, 3, 4, 5}) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 1. neighbours = net.getNeighbours(net.getNeuron(1)); for (long nId : new long[] {0, 2, 3, 4, 5 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 2. neighbours = net.getNeighbours(net.getNeuron(2)); for (long nId : new long[] {0, 1, 3, 4, 5 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 3. neighbours = net.getNeighbours(net.getNeuron(3)); for (long nId : new long[] {0, 1, 2, 4, 5, 6, 7, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(8, neighbours.size()); // Neuron 4. neighbours = net.getNeighbours(net.getNeuron(4)); for (long nId : new long[] {0, 1, 2, 3, 5, 6, 7, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(8, neighbours.size()); // Neuron 5. neighbours = net.getNeighbours(net.getNeuron(5)); for (long nId : new long[] {0, 1, 2, 3, 4, 6, 7, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(8, neighbours.size()); // Neuron 6. neighbours = net.getNeighbours(net.getNeuron(6)); for (long nId : new long[] {3, 4, 5, 7, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 7. neighbours = net.getNeighbours(net.getNeuron(7)); for (long nId : new long[] {3, 4, 5, 6, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 8. neighbours = net.getNeighbours(net.getNeuron(8)); for (long nId : new long[] {3, 4, 5, 6, 7 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 * | | | * | | | * 6-----7-----8 */ @Test public void test3x3CylinderNetwork2() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(3, false, 3, false, SquareNeighbourhood.MOORE, initArray).getNetwork(); Collection<Neuron> neighbours; // Neuron 0. neighbours = net.getNeighbours(net.getNeuron(0)); for (long nId : new long[] {1, 3, 4}) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 1. neighbours = net.getNeighbours(net.getNeuron(1)); for (long nId : new long[] {0, 2, 3, 4, 5 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 2. neighbours = net.getNeighbours(net.getNeuron(2)); for (long nId : new long[] {1, 4, 5 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 3. neighbours = net.getNeighbours(net.getNeuron(3)); for (long nId : new long[] {0, 1, 4, 6, 7 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 4. neighbours = net.getNeighbours(net.getNeuron(4)); for (long nId : new long[] {0, 1, 2, 3, 5, 6, 7, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(8, neighbours.size()); // Neuron 5. neighbours = net.getNeighbours(net.getNeuron(5)); for (long nId : new long[] {1, 2, 4, 7, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 6. neighbours = net.getNeighbours(net.getNeuron(6)); for (long nId : new long[] {3, 4, 7 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); // Neuron 7. neighbours = net.getNeighbours(net.getNeuron(7)); for (long nId : new long[] {3, 4, 5, 6, 8 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(5, neighbours.size()); // Neuron 8. neighbours = net.getNeighbours(net.getNeuron(8)); for (long nId : new long[] {4, 5, 7 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(3, neighbours.size()); } /* * Test assumes that the network is * * 0-----1-----2-----3-----4 * | | | | | * | | | | | * 5-----6-----7-----8-----9 * | | | | | * | | | | | * 10----11----12----13---14 * | | | | | * | | | | | * 15----16----17----18---19 * | | | | | * | | | | | * 20----21----22----23---24 */ @Test public void testConcentricNeighbourhood() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(5, true, 5, true, SquareNeighbourhood.VON_NEUMANN, initArray).getNetwork(); Collection<Neuron> neighbours; Collection<Neuron> exclude = new HashSet<>(); // Level-1 neighbourhood. neighbours = net.getNeighbours(net.getNeuron(12)); for (long nId : new long[] {7, 11, 13, 17 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(4, neighbours.size()); // 1. Add the neuron to the "exclude" list. exclude.add(net.getNeuron(12)); // 2. Add all neurons from level-1 neighbourhood. exclude.addAll(neighbours); // 3. Retrieve level-2 neighbourhood. neighbours = net.getNeighbours(neighbours, exclude); for (long nId : new long[] {6, 8, 16, 18, 2, 10, 14, 22 }) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(8, neighbours.size()); } /* * Test assumes that the network is * * 0-----1-----2-----3-----4 * | | | | | * | | | | | * 5-----6-----7-----8-----9 * | | | | | * | | | | | * 10----11----12----13---14 * | | | | | * | | | | | * 15----16----17----18---19 * | | | | | * | | | | | * 20----21----22----23---24 */ @Test public void testConcentricNeighbourhood2() { final FeatureInitializer[] initArray = {init}; final Network net = new NeuronSquareMesh2D(5, true, 5, true, SquareNeighbourhood.MOORE, initArray).getNetwork(); Collection<Neuron> neighbours; Collection<Neuron> exclude = new HashSet<>(); // Level-1 neighbourhood. neighbours = net.getNeighbours(net.getNeuron(8)); for (long nId : new long[] {2, 3, 4, 7, 9, 12, 13, 14}) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(8, neighbours.size()); // 1. Add the neuron to the "exclude" list. exclude.add(net.getNeuron(8)); // 2. Add all neurons from level-1 neighbourhood. exclude.addAll(neighbours); // 3. Retrieve level-2 neighbourhood. neighbours = net.getNeighbours(neighbours, exclude); for (long nId : new long[] {1, 6, 11, 16, 17, 18, 19, 15, 10, 5, 0, 20, 24, 23, 22, 21}) { Assert.assertTrue(neighbours.contains(net.getNeuron(nId))); } // Ensures that no other neurons is in the neighbourhood set. Assert.assertEquals(16, neighbours.size()); } /* * Test assumes that the network is * * 0-----1 * | | * | | * 2-----3 */ @Test public void testGetNeuron() { final FeatureInitializer[] initArray = {init}; final NeuronSquareMesh2D net = new NeuronSquareMesh2D(2, false, 2, true, SquareNeighbourhood.VON_NEUMANN, initArray); Assert.assertEquals(0, net.getNeuron(0, 0).getIdentifier()); Assert.assertEquals(1, net.getNeuron(0, 1).getIdentifier()); Assert.assertEquals(2, net.getNeuron(1, 0).getIdentifier()); Assert.assertEquals(3, net.getNeuron(1, 1).getIdentifier()); try { net.getNeuron(2, 0); Assert.fail("exception expected"); } catch (IllegalArgumentException e) { // Expected. } try { net.getNeuron(0, 2); Assert.fail("exception expected"); } catch (IllegalArgumentException e) { // Expected. } try { net.getNeuron(-1, 0); Assert.fail("exception expected"); } catch (IllegalArgumentException e) { // Expected. } try { net.getNeuron(0, -1); Assert.fail("exception expected"); } catch (IllegalArgumentException e) { // Expected. } } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 * | | | * | | | * 6-----7-----8 */ @Test public void testGetNeuronAlongDirection() { final FeatureInitializer[] initArray = {init}; final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, false, 3, false, SquareNeighbourhood.VON_NEUMANN, initArray); Assert.assertEquals(0, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); Assert.assertEquals(1, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.CENTER, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); Assert.assertEquals(2, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); Assert.assertEquals(3, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.CENTER).getIdentifier()); Assert.assertEquals(4, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.CENTER, NeuronSquareMesh2D.VerticalDirection.CENTER).getIdentifier()); Assert.assertEquals(5, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.CENTER).getIdentifier()); Assert.assertEquals(6, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.DOWN).getIdentifier()); Assert.assertEquals(7, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.CENTER, NeuronSquareMesh2D.VerticalDirection.DOWN).getIdentifier()); Assert.assertEquals(8, net.getNeuron(1, 1, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.DOWN).getIdentifier()); // Locations not in map. Assert.assertNull(net.getNeuron(0, 1, NeuronSquareMesh2D.HorizontalDirection.CENTER, NeuronSquareMesh2D.VerticalDirection.UP)); Assert.assertNull(net.getNeuron(1, 0, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.CENTER)); Assert.assertNull(net.getNeuron(2, 1, NeuronSquareMesh2D.HorizontalDirection.CENTER, NeuronSquareMesh2D.VerticalDirection.DOWN)); Assert.assertNull(net.getNeuron(1, 2, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.CENTER)); } /* * Test assumes that the network is * * 0-----1-----2 * | | | * | | | * 3-----4-----5 * | | | * | | | * 6-----7-----8 */ @Test public void testGetNeuronAlongDirectionWrappedMap() { final FeatureInitializer[] initArray = {init}; final NeuronSquareMesh2D net = new NeuronSquareMesh2D(3, true, 3, true, SquareNeighbourhood.VON_NEUMANN, initArray); // No wrapping. Assert.assertEquals(3, net.getNeuron(0, 0, NeuronSquareMesh2D.HorizontalDirection.CENTER, NeuronSquareMesh2D.VerticalDirection.DOWN).getIdentifier()); // With wrapping. Assert.assertEquals(2, net.getNeuron(0, 0, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.CENTER).getIdentifier()); Assert.assertEquals(7, net.getNeuron(0, 0, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); Assert.assertEquals(8, net.getNeuron(0, 0, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); Assert.assertEquals(6, net.getNeuron(0, 0, NeuronSquareMesh2D.HorizontalDirection.CENTER, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); Assert.assertEquals(5, net.getNeuron(0, 0, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.DOWN).getIdentifier()); // No wrapping. Assert.assertEquals(1, net.getNeuron(1, 2, NeuronSquareMesh2D.HorizontalDirection.LEFT, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); // With wrapping. Assert.assertEquals(0, net.getNeuron(1, 2, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.UP).getIdentifier()); Assert.assertEquals(3, net.getNeuron(1, 2, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.CENTER).getIdentifier()); Assert.assertEquals(6, net.getNeuron(1, 2, NeuronSquareMesh2D.HorizontalDirection.RIGHT, NeuronSquareMesh2D.VerticalDirection.DOWN).getIdentifier()); } @Test public void testIterator() { final FeatureInitializer[] initArray = {init}; final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true, 3, true, SquareNeighbourhood.VON_NEUMANN, initArray); final Set<Neuron> fromMap = new HashSet<>(); for (Neuron n : map) { fromMap.add(n); } final Network net = map.getNetwork(); final Set<Neuron> fromNet = new HashSet<>(); for (Neuron n : net) { fromNet.add(n); } for (Neuron n : fromMap) { Assert.assertTrue(fromNet.contains(n)); } for (Neuron n : fromNet) { Assert.assertTrue(fromMap.contains(n)); } } @Test public void testDataVisualization() { final FeatureInitializer[] initArray = {init}; final NeuronSquareMesh2D map = new NeuronSquareMesh2D(3, true, 3, true, SquareNeighbourhood.VON_NEUMANN, initArray); // Trivial test: Use neurons' features as data. final List<double[]> data = StreamSupport.stream(map.spliterator(), false) .map(n -> n.getFeatures()) .collect(Collectors.toList()); final NeuronSquareMesh2D.DataVisualization v = map.computeQualityIndicators(data); final int numRows = map.getNumberOfRows(); final int numCols = map.getNumberOfColumns(); // Test hits. final double[][] hits = v.getNormalizedHits(); final double expectedHits = 1d / (numRows * numCols); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { Assert.assertEquals(expectedHits, hits[i][j], 0d); } } // Test quantization error. final double[][] qe = v.getQuantizationError(); final double expectedQE = 0; for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { Assert.assertEquals(expectedQE, qe[i][j], 0d); } } } }
googleapis/google-cloud-java
36,367
java-os-config/proto-google-cloud-os-config-v1alpha/src/main/java/com/google/cloud/osconfig/v1alpha/ListInventoriesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/osconfig/v1alpha/inventory.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.osconfig.v1alpha; /** * * * <pre> * A response message for listing inventory data for all VMs in a specified * location. * </pre> * * Protobuf type {@code google.cloud.osconfig.v1alpha.ListInventoriesResponse} */ public final class ListInventoriesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.osconfig.v1alpha.ListInventoriesResponse) ListInventoriesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListInventoriesResponse.newBuilder() to construct. private ListInventoriesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListInventoriesResponse() { inventories_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListInventoriesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.osconfig.v1alpha.Inventories .internal_static_google_cloud_osconfig_v1alpha_ListInventoriesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.osconfig.v1alpha.Inventories .internal_static_google_cloud_osconfig_v1alpha_ListInventoriesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.osconfig.v1alpha.ListInventoriesResponse.class, com.google.cloud.osconfig.v1alpha.ListInventoriesResponse.Builder.class); } public static final int INVENTORIES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.osconfig.v1alpha.Inventory> inventories_; /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.osconfig.v1alpha.Inventory> getInventoriesList() { return inventories_; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.osconfig.v1alpha.InventoryOrBuilder> getInventoriesOrBuilderList() { return inventories_; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ @java.lang.Override public int getInventoriesCount() { return inventories_.size(); } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ @java.lang.Override public com.google.cloud.osconfig.v1alpha.Inventory getInventories(int index) { return inventories_.get(index); } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ @java.lang.Override public com.google.cloud.osconfig.v1alpha.InventoryOrBuilder getInventoriesOrBuilder(int index) { return inventories_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The pagination token to retrieve the next page of inventory objects. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * The pagination token to retrieve the next page of inventory objects. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < inventories_.size(); i++) { output.writeMessage(1, inventories_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < inventories_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, inventories_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.osconfig.v1alpha.ListInventoriesResponse)) { return super.equals(obj); } com.google.cloud.osconfig.v1alpha.ListInventoriesResponse other = (com.google.cloud.osconfig.v1alpha.ListInventoriesResponse) obj; if (!getInventoriesList().equals(other.getInventoriesList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getInventoriesCount() > 0) { hash = (37 * hash) + INVENTORIES_FIELD_NUMBER; hash = (53 * hash) + getInventoriesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.osconfig.v1alpha.ListInventoriesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A response message for listing inventory data for all VMs in a specified * location. * </pre> * * Protobuf type {@code google.cloud.osconfig.v1alpha.ListInventoriesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.osconfig.v1alpha.ListInventoriesResponse) com.google.cloud.osconfig.v1alpha.ListInventoriesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.osconfig.v1alpha.Inventories .internal_static_google_cloud_osconfig_v1alpha_ListInventoriesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.osconfig.v1alpha.Inventories .internal_static_google_cloud_osconfig_v1alpha_ListInventoriesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.osconfig.v1alpha.ListInventoriesResponse.class, com.google.cloud.osconfig.v1alpha.ListInventoriesResponse.Builder.class); } // Construct using com.google.cloud.osconfig.v1alpha.ListInventoriesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (inventoriesBuilder_ == null) { inventories_ = java.util.Collections.emptyList(); } else { inventories_ = null; inventoriesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.osconfig.v1alpha.Inventories .internal_static_google_cloud_osconfig_v1alpha_ListInventoriesResponse_descriptor; } @java.lang.Override public com.google.cloud.osconfig.v1alpha.ListInventoriesResponse getDefaultInstanceForType() { return com.google.cloud.osconfig.v1alpha.ListInventoriesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.osconfig.v1alpha.ListInventoriesResponse build() { com.google.cloud.osconfig.v1alpha.ListInventoriesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.osconfig.v1alpha.ListInventoriesResponse buildPartial() { com.google.cloud.osconfig.v1alpha.ListInventoriesResponse result = new com.google.cloud.osconfig.v1alpha.ListInventoriesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.osconfig.v1alpha.ListInventoriesResponse result) { if (inventoriesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { inventories_ = java.util.Collections.unmodifiableList(inventories_); bitField0_ = (bitField0_ & ~0x00000001); } result.inventories_ = inventories_; } else { result.inventories_ = inventoriesBuilder_.build(); } } private void buildPartial0(com.google.cloud.osconfig.v1alpha.ListInventoriesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.osconfig.v1alpha.ListInventoriesResponse) { return mergeFrom((com.google.cloud.osconfig.v1alpha.ListInventoriesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.osconfig.v1alpha.ListInventoriesResponse other) { if (other == com.google.cloud.osconfig.v1alpha.ListInventoriesResponse.getDefaultInstance()) return this; if (inventoriesBuilder_ == null) { if (!other.inventories_.isEmpty()) { if (inventories_.isEmpty()) { inventories_ = other.inventories_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureInventoriesIsMutable(); inventories_.addAll(other.inventories_); } onChanged(); } } else { if (!other.inventories_.isEmpty()) { if (inventoriesBuilder_.isEmpty()) { inventoriesBuilder_.dispose(); inventoriesBuilder_ = null; inventories_ = other.inventories_; bitField0_ = (bitField0_ & ~0x00000001); inventoriesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getInventoriesFieldBuilder() : null; } else { inventoriesBuilder_.addAllMessages(other.inventories_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.osconfig.v1alpha.Inventory m = input.readMessage( com.google.cloud.osconfig.v1alpha.Inventory.parser(), extensionRegistry); if (inventoriesBuilder_ == null) { ensureInventoriesIsMutable(); inventories_.add(m); } else { inventoriesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.osconfig.v1alpha.Inventory> inventories_ = java.util.Collections.emptyList(); private void ensureInventoriesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { inventories_ = new java.util.ArrayList<com.google.cloud.osconfig.v1alpha.Inventory>(inventories_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.osconfig.v1alpha.Inventory, com.google.cloud.osconfig.v1alpha.Inventory.Builder, com.google.cloud.osconfig.v1alpha.InventoryOrBuilder> inventoriesBuilder_; /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public java.util.List<com.google.cloud.osconfig.v1alpha.Inventory> getInventoriesList() { if (inventoriesBuilder_ == null) { return java.util.Collections.unmodifiableList(inventories_); } else { return inventoriesBuilder_.getMessageList(); } } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public int getInventoriesCount() { if (inventoriesBuilder_ == null) { return inventories_.size(); } else { return inventoriesBuilder_.getCount(); } } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public com.google.cloud.osconfig.v1alpha.Inventory getInventories(int index) { if (inventoriesBuilder_ == null) { return inventories_.get(index); } else { return inventoriesBuilder_.getMessage(index); } } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder setInventories(int index, com.google.cloud.osconfig.v1alpha.Inventory value) { if (inventoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInventoriesIsMutable(); inventories_.set(index, value); onChanged(); } else { inventoriesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder setInventories( int index, com.google.cloud.osconfig.v1alpha.Inventory.Builder builderForValue) { if (inventoriesBuilder_ == null) { ensureInventoriesIsMutable(); inventories_.set(index, builderForValue.build()); onChanged(); } else { inventoriesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder addInventories(com.google.cloud.osconfig.v1alpha.Inventory value) { if (inventoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInventoriesIsMutable(); inventories_.add(value); onChanged(); } else { inventoriesBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder addInventories(int index, com.google.cloud.osconfig.v1alpha.Inventory value) { if (inventoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInventoriesIsMutable(); inventories_.add(index, value); onChanged(); } else { inventoriesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder addInventories( com.google.cloud.osconfig.v1alpha.Inventory.Builder builderForValue) { if (inventoriesBuilder_ == null) { ensureInventoriesIsMutable(); inventories_.add(builderForValue.build()); onChanged(); } else { inventoriesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder addInventories( int index, com.google.cloud.osconfig.v1alpha.Inventory.Builder builderForValue) { if (inventoriesBuilder_ == null) { ensureInventoriesIsMutable(); inventories_.add(index, builderForValue.build()); onChanged(); } else { inventoriesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder addAllInventories( java.lang.Iterable<? extends com.google.cloud.osconfig.v1alpha.Inventory> values) { if (inventoriesBuilder_ == null) { ensureInventoriesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, inventories_); onChanged(); } else { inventoriesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder clearInventories() { if (inventoriesBuilder_ == null) { inventories_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { inventoriesBuilder_.clear(); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public Builder removeInventories(int index) { if (inventoriesBuilder_ == null) { ensureInventoriesIsMutable(); inventories_.remove(index); onChanged(); } else { inventoriesBuilder_.remove(index); } return this; } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public com.google.cloud.osconfig.v1alpha.Inventory.Builder getInventoriesBuilder(int index) { return getInventoriesFieldBuilder().getBuilder(index); } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public com.google.cloud.osconfig.v1alpha.InventoryOrBuilder getInventoriesOrBuilder(int index) { if (inventoriesBuilder_ == null) { return inventories_.get(index); } else { return inventoriesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public java.util.List<? extends com.google.cloud.osconfig.v1alpha.InventoryOrBuilder> getInventoriesOrBuilderList() { if (inventoriesBuilder_ != null) { return inventoriesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(inventories_); } } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public com.google.cloud.osconfig.v1alpha.Inventory.Builder addInventoriesBuilder() { return getInventoriesFieldBuilder() .addBuilder(com.google.cloud.osconfig.v1alpha.Inventory.getDefaultInstance()); } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public com.google.cloud.osconfig.v1alpha.Inventory.Builder addInventoriesBuilder(int index) { return getInventoriesFieldBuilder() .addBuilder(index, com.google.cloud.osconfig.v1alpha.Inventory.getDefaultInstance()); } /** * * * <pre> * List of inventory objects. * </pre> * * <code>repeated .google.cloud.osconfig.v1alpha.Inventory inventories = 1;</code> */ public java.util.List<com.google.cloud.osconfig.v1alpha.Inventory.Builder> getInventoriesBuilderList() { return getInventoriesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.osconfig.v1alpha.Inventory, com.google.cloud.osconfig.v1alpha.Inventory.Builder, com.google.cloud.osconfig.v1alpha.InventoryOrBuilder> getInventoriesFieldBuilder() { if (inventoriesBuilder_ == null) { inventoriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.osconfig.v1alpha.Inventory, com.google.cloud.osconfig.v1alpha.Inventory.Builder, com.google.cloud.osconfig.v1alpha.InventoryOrBuilder>( inventories_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); inventories_ = null; } return inventoriesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The pagination token to retrieve the next page of inventory objects. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The pagination token to retrieve the next page of inventory objects. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The pagination token to retrieve the next page of inventory objects. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The pagination token to retrieve the next page of inventory objects. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The pagination token to retrieve the next page of inventory objects. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.osconfig.v1alpha.ListInventoriesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.osconfig.v1alpha.ListInventoriesResponse) private static final com.google.cloud.osconfig.v1alpha.ListInventoriesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.osconfig.v1alpha.ListInventoriesResponse(); } public static com.google.cloud.osconfig.v1alpha.ListInventoriesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListInventoriesResponse> PARSER = new com.google.protobuf.AbstractParser<ListInventoriesResponse>() { @java.lang.Override public ListInventoriesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListInventoriesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListInventoriesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.osconfig.v1alpha.ListInventoriesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,487
java-container/proto-google-cloud-container-v1/src/main/java/com/google/container/v1/DesiredAdditionalIPRangesConfig.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1/cluster_service.proto // Protobuf Java Version: 3.25.8 package com.google.container.v1; /** * * * <pre> * DesiredAdditionalIPRangesConfig is a wrapper used for cluster update * operation and contains multiple AdditionalIPRangesConfigs. * </pre> * * Protobuf type {@code google.container.v1.DesiredAdditionalIPRangesConfig} */ public final class DesiredAdditionalIPRangesConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1.DesiredAdditionalIPRangesConfig) DesiredAdditionalIPRangesConfigOrBuilder { private static final long serialVersionUID = 0L; // Use DesiredAdditionalIPRangesConfig.newBuilder() to construct. private DesiredAdditionalIPRangesConfig( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DesiredAdditionalIPRangesConfig() { additionalIpRangesConfigs_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DesiredAdditionalIPRangesConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_DesiredAdditionalIPRangesConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_DesiredAdditionalIPRangesConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.DesiredAdditionalIPRangesConfig.class, com.google.container.v1.DesiredAdditionalIPRangesConfig.Builder.class); } public static final int ADDITIONAL_IP_RANGES_CONFIGS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.container.v1.AdditionalIPRangesConfig> additionalIpRangesConfigs_; /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code>repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ @java.lang.Override public java.util.List<com.google.container.v1.AdditionalIPRangesConfig> getAdditionalIpRangesConfigsList() { return additionalIpRangesConfigs_; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code>repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ @java.lang.Override public java.util.List<? extends com.google.container.v1.AdditionalIPRangesConfigOrBuilder> getAdditionalIpRangesConfigsOrBuilderList() { return additionalIpRangesConfigs_; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code>repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ @java.lang.Override public int getAdditionalIpRangesConfigsCount() { return additionalIpRangesConfigs_.size(); } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code>repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ @java.lang.Override public com.google.container.v1.AdditionalIPRangesConfig getAdditionalIpRangesConfigs(int index) { return additionalIpRangesConfigs_.get(index); } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code>repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ @java.lang.Override public com.google.container.v1.AdditionalIPRangesConfigOrBuilder getAdditionalIpRangesConfigsOrBuilder(int index) { return additionalIpRangesConfigs_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < additionalIpRangesConfigs_.size(); i++) { output.writeMessage(1, additionalIpRangesConfigs_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < additionalIpRangesConfigs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, additionalIpRangesConfigs_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.container.v1.DesiredAdditionalIPRangesConfig)) { return super.equals(obj); } com.google.container.v1.DesiredAdditionalIPRangesConfig other = (com.google.container.v1.DesiredAdditionalIPRangesConfig) obj; if (!getAdditionalIpRangesConfigsList().equals(other.getAdditionalIpRangesConfigsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getAdditionalIpRangesConfigsCount() > 0) { hash = (37 * hash) + ADDITIONAL_IP_RANGES_CONFIGS_FIELD_NUMBER; hash = (53 * hash) + getAdditionalIpRangesConfigsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.container.v1.DesiredAdditionalIPRangesConfig prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * DesiredAdditionalIPRangesConfig is a wrapper used for cluster update * operation and contains multiple AdditionalIPRangesConfigs. * </pre> * * Protobuf type {@code google.container.v1.DesiredAdditionalIPRangesConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1.DesiredAdditionalIPRangesConfig) com.google.container.v1.DesiredAdditionalIPRangesConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_DesiredAdditionalIPRangesConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_DesiredAdditionalIPRangesConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1.DesiredAdditionalIPRangesConfig.class, com.google.container.v1.DesiredAdditionalIPRangesConfig.Builder.class); } // Construct using com.google.container.v1.DesiredAdditionalIPRangesConfig.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (additionalIpRangesConfigsBuilder_ == null) { additionalIpRangesConfigs_ = java.util.Collections.emptyList(); } else { additionalIpRangesConfigs_ = null; additionalIpRangesConfigsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1.ClusterServiceProto .internal_static_google_container_v1_DesiredAdditionalIPRangesConfig_descriptor; } @java.lang.Override public com.google.container.v1.DesiredAdditionalIPRangesConfig getDefaultInstanceForType() { return com.google.container.v1.DesiredAdditionalIPRangesConfig.getDefaultInstance(); } @java.lang.Override public com.google.container.v1.DesiredAdditionalIPRangesConfig build() { com.google.container.v1.DesiredAdditionalIPRangesConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1.DesiredAdditionalIPRangesConfig buildPartial() { com.google.container.v1.DesiredAdditionalIPRangesConfig result = new com.google.container.v1.DesiredAdditionalIPRangesConfig(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.container.v1.DesiredAdditionalIPRangesConfig result) { if (additionalIpRangesConfigsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { additionalIpRangesConfigs_ = java.util.Collections.unmodifiableList(additionalIpRangesConfigs_); bitField0_ = (bitField0_ & ~0x00000001); } result.additionalIpRangesConfigs_ = additionalIpRangesConfigs_; } else { result.additionalIpRangesConfigs_ = additionalIpRangesConfigsBuilder_.build(); } } private void buildPartial0(com.google.container.v1.DesiredAdditionalIPRangesConfig result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.container.v1.DesiredAdditionalIPRangesConfig) { return mergeFrom((com.google.container.v1.DesiredAdditionalIPRangesConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1.DesiredAdditionalIPRangesConfig other) { if (other == com.google.container.v1.DesiredAdditionalIPRangesConfig.getDefaultInstance()) return this; if (additionalIpRangesConfigsBuilder_ == null) { if (!other.additionalIpRangesConfigs_.isEmpty()) { if (additionalIpRangesConfigs_.isEmpty()) { additionalIpRangesConfigs_ = other.additionalIpRangesConfigs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.addAll(other.additionalIpRangesConfigs_); } onChanged(); } } else { if (!other.additionalIpRangesConfigs_.isEmpty()) { if (additionalIpRangesConfigsBuilder_.isEmpty()) { additionalIpRangesConfigsBuilder_.dispose(); additionalIpRangesConfigsBuilder_ = null; additionalIpRangesConfigs_ = other.additionalIpRangesConfigs_; bitField0_ = (bitField0_ & ~0x00000001); additionalIpRangesConfigsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getAdditionalIpRangesConfigsFieldBuilder() : null; } else { additionalIpRangesConfigsBuilder_.addAllMessages(other.additionalIpRangesConfigs_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.container.v1.AdditionalIPRangesConfig m = input.readMessage( com.google.container.v1.AdditionalIPRangesConfig.parser(), extensionRegistry); if (additionalIpRangesConfigsBuilder_ == null) { ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.add(m); } else { additionalIpRangesConfigsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.container.v1.AdditionalIPRangesConfig> additionalIpRangesConfigs_ = java.util.Collections.emptyList(); private void ensureAdditionalIpRangesConfigsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { additionalIpRangesConfigs_ = new java.util.ArrayList<com.google.container.v1.AdditionalIPRangesConfig>( additionalIpRangesConfigs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1.AdditionalIPRangesConfig, com.google.container.v1.AdditionalIPRangesConfig.Builder, com.google.container.v1.AdditionalIPRangesConfigOrBuilder> additionalIpRangesConfigsBuilder_; /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public java.util.List<com.google.container.v1.AdditionalIPRangesConfig> getAdditionalIpRangesConfigsList() { if (additionalIpRangesConfigsBuilder_ == null) { return java.util.Collections.unmodifiableList(additionalIpRangesConfigs_); } else { return additionalIpRangesConfigsBuilder_.getMessageList(); } } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public int getAdditionalIpRangesConfigsCount() { if (additionalIpRangesConfigsBuilder_ == null) { return additionalIpRangesConfigs_.size(); } else { return additionalIpRangesConfigsBuilder_.getCount(); } } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public com.google.container.v1.AdditionalIPRangesConfig getAdditionalIpRangesConfigs( int index) { if (additionalIpRangesConfigsBuilder_ == null) { return additionalIpRangesConfigs_.get(index); } else { return additionalIpRangesConfigsBuilder_.getMessage(index); } } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder setAdditionalIpRangesConfigs( int index, com.google.container.v1.AdditionalIPRangesConfig value) { if (additionalIpRangesConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.set(index, value); onChanged(); } else { additionalIpRangesConfigsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder setAdditionalIpRangesConfigs( int index, com.google.container.v1.AdditionalIPRangesConfig.Builder builderForValue) { if (additionalIpRangesConfigsBuilder_ == null) { ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.set(index, builderForValue.build()); onChanged(); } else { additionalIpRangesConfigsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder addAdditionalIpRangesConfigs( com.google.container.v1.AdditionalIPRangesConfig value) { if (additionalIpRangesConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.add(value); onChanged(); } else { additionalIpRangesConfigsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder addAdditionalIpRangesConfigs( int index, com.google.container.v1.AdditionalIPRangesConfig value) { if (additionalIpRangesConfigsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.add(index, value); onChanged(); } else { additionalIpRangesConfigsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder addAdditionalIpRangesConfigs( com.google.container.v1.AdditionalIPRangesConfig.Builder builderForValue) { if (additionalIpRangesConfigsBuilder_ == null) { ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.add(builderForValue.build()); onChanged(); } else { additionalIpRangesConfigsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder addAdditionalIpRangesConfigs( int index, com.google.container.v1.AdditionalIPRangesConfig.Builder builderForValue) { if (additionalIpRangesConfigsBuilder_ == null) { ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.add(index, builderForValue.build()); onChanged(); } else { additionalIpRangesConfigsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder addAllAdditionalIpRangesConfigs( java.lang.Iterable<? extends com.google.container.v1.AdditionalIPRangesConfig> values) { if (additionalIpRangesConfigsBuilder_ == null) { ensureAdditionalIpRangesConfigsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, additionalIpRangesConfigs_); onChanged(); } else { additionalIpRangesConfigsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder clearAdditionalIpRangesConfigs() { if (additionalIpRangesConfigsBuilder_ == null) { additionalIpRangesConfigs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { additionalIpRangesConfigsBuilder_.clear(); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public Builder removeAdditionalIpRangesConfigs(int index) { if (additionalIpRangesConfigsBuilder_ == null) { ensureAdditionalIpRangesConfigsIsMutable(); additionalIpRangesConfigs_.remove(index); onChanged(); } else { additionalIpRangesConfigsBuilder_.remove(index); } return this; } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public com.google.container.v1.AdditionalIPRangesConfig.Builder getAdditionalIpRangesConfigsBuilder(int index) { return getAdditionalIpRangesConfigsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public com.google.container.v1.AdditionalIPRangesConfigOrBuilder getAdditionalIpRangesConfigsOrBuilder(int index) { if (additionalIpRangesConfigsBuilder_ == null) { return additionalIpRangesConfigs_.get(index); } else { return additionalIpRangesConfigsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public java.util.List<? extends com.google.container.v1.AdditionalIPRangesConfigOrBuilder> getAdditionalIpRangesConfigsOrBuilderList() { if (additionalIpRangesConfigsBuilder_ != null) { return additionalIpRangesConfigsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(additionalIpRangesConfigs_); } } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public com.google.container.v1.AdditionalIPRangesConfig.Builder addAdditionalIpRangesConfigsBuilder() { return getAdditionalIpRangesConfigsFieldBuilder() .addBuilder(com.google.container.v1.AdditionalIPRangesConfig.getDefaultInstance()); } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public com.google.container.v1.AdditionalIPRangesConfig.Builder addAdditionalIpRangesConfigsBuilder(int index) { return getAdditionalIpRangesConfigsFieldBuilder() .addBuilder(index, com.google.container.v1.AdditionalIPRangesConfig.getDefaultInstance()); } /** * * * <pre> * List of additional IP ranges configs where each AdditionalIPRangesConfig * corresponds to one subnetwork's IP ranges * </pre> * * <code> * repeated .google.container.v1.AdditionalIPRangesConfig additional_ip_ranges_configs = 1; * </code> */ public java.util.List<com.google.container.v1.AdditionalIPRangesConfig.Builder> getAdditionalIpRangesConfigsBuilderList() { return getAdditionalIpRangesConfigsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1.AdditionalIPRangesConfig, com.google.container.v1.AdditionalIPRangesConfig.Builder, com.google.container.v1.AdditionalIPRangesConfigOrBuilder> getAdditionalIpRangesConfigsFieldBuilder() { if (additionalIpRangesConfigsBuilder_ == null) { additionalIpRangesConfigsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.container.v1.AdditionalIPRangesConfig, com.google.container.v1.AdditionalIPRangesConfig.Builder, com.google.container.v1.AdditionalIPRangesConfigOrBuilder>( additionalIpRangesConfigs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); additionalIpRangesConfigs_ = null; } return additionalIpRangesConfigsBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.container.v1.DesiredAdditionalIPRangesConfig) } // @@protoc_insertion_point(class_scope:google.container.v1.DesiredAdditionalIPRangesConfig) private static final com.google.container.v1.DesiredAdditionalIPRangesConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1.DesiredAdditionalIPRangesConfig(); } public static com.google.container.v1.DesiredAdditionalIPRangesConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DesiredAdditionalIPRangesConfig> PARSER = new com.google.protobuf.AbstractParser<DesiredAdditionalIPRangesConfig>() { @java.lang.Override public DesiredAdditionalIPRangesConfig parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<DesiredAdditionalIPRangesConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DesiredAdditionalIPRangesConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1.DesiredAdditionalIPRangesConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/depan
36,842
DepanViewDoc/prod/src/com/google/devtools/depan/eclipse/cm/ColorMapDefGistHeat.java
// This file is automatically generated by a script (generateColorMaps.py). // Do not modify it, or changes will be lost when the script is run again. /* * This file was generated using data provided by the python library matplotlib * which is Copyright (c) 2002-2004 John D. Hunter; All Rights Reserved * * For the rest of the code source, the following copyright and license * applies. * * Copyright 2008 The Depan Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.depan.eclipse.cm; public final class ColorMapDefGistHeat { private ColorMapDefGistHeat() { } public static final float[][][] CM = { { // red {0.0f, 0.0f, 0.0f}, {0.00420168088749f, 0.00392156885937f, 0.00392156885937f}, {0.00840336177498f, 0.00784313771874f, 0.00784313771874f}, {0.0126050421968f, 0.0156862754375f, 0.0156862754375f}, {0.01680672355f, 0.0196078438312f, 0.0196078438312f}, {0.0210084039718f, 0.0274509806186f, 0.0274509806186f}, {0.0252100843936f, 0.0313725508749f, 0.0313725508749f}, {0.0294117648154f, 0.0392156876624f, 0.0392156876624f}, {0.0336134470999f, 0.0431372560561f, 0.0431372560561f}, {0.0378151275218f, 0.0509803928435f, 0.0509803928435f}, {0.0420168079436f, 0.0588235296309f, 0.0588235296309f}, {0.0462184883654f, 0.0666666701436f, 0.0666666701436f}, {0.0504201687872f, 0.0705882385373f, 0.0705882385373f}, {0.0546218492091f, 0.0784313753247f, 0.0784313753247f}, {0.0588235296309f, 0.0823529437184f, 0.0823529437184f}, {0.063025213778f, 0.0901960805058f, 0.0901960805058f}, {0.0672268941998f, 0.0941176488996f, 0.0941176488996f}, {0.0714285746217f, 0.101960785687f, 0.101960785687f}, {0.0756302550435f, 0.105882354081f, 0.105882354081f}, {0.0798319354653f, 0.109803922474f, 0.109803922474f}, {0.0840336158872f, 0.117647059262f, 0.117647059262f}, {0.088235296309f, 0.121568627656f, 0.121568627656f}, {0.0924369767308f, 0.129411771894f, 0.129411771894f}, {0.0966386571527f, 0.133333340287f, 0.133333340287f}, {0.100840337574f, 0.141176477075f, 0.141176477075f}, {0.105042017996f, 0.145098045468f, 0.145098045468f}, {0.109243698418f, 0.152941182256f, 0.152941182256f}, {0.11344537884f, 0.156862750649f, 0.156862750649f}, {0.117647059262f, 0.164705887437f, 0.164705887437f}, {0.121848739684f, 0.168627455831f, 0.168627455831f}, {0.126050427556f, 0.180392161012f, 0.180392161012f}, {0.130252107978f, 0.184313729405f, 0.184313729405f}, {0.1344537884f, 0.192156866193f, 0.192156866193f}, {0.138655468822f, 0.196078434587f, 0.196078434587f}, {0.142857149243f, 0.203921571374f, 0.203921571374f}, {0.147058829665f, 0.207843139768f, 0.207843139768f}, {0.151260510087f, 0.215686276555f, 0.215686276555f}, {0.155462190509f, 0.219607844949f, 0.219607844949f}, {0.159663870931f, 0.223529413342f, 0.223529413342f}, {0.163865551353f, 0.23137255013f, 0.23137255013f}, {0.168067231774f, 0.235294118524f, 0.235294118524f}, {0.172268912196f, 0.243137255311f, 0.243137255311f}, {0.176470592618f, 0.247058823705f, 0.247058823705f}, {0.18067227304f, 0.254901975393f, 0.254901975393f}, {0.184873953462f, 0.258823543787f, 0.258823543787f}, {0.189075633883f, 0.266666680574f, 0.266666680574f}, {0.193277314305f, 0.270588248968f, 0.270588248968f}, {0.197478994727f, 0.274509817362f, 0.274509817362f}, {0.201680675149f, 0.282352954149f, 0.282352954149f}, {0.205882355571f, 0.286274522543f, 0.286274522543f}, {0.210084035993f, 0.298039227724f, 0.298039227724f}, {0.214285716414f, 0.305882364511f, 0.305882364511f}, {0.218487396836f, 0.309803932905f, 0.309803932905f}, {0.222689077258f, 0.317647069693f, 0.317647069693f}, {0.22689075768f, 0.321568638086f, 0.321568638086f}, {0.231092438102f, 0.329411774874f, 0.329411774874f}, {0.235294118524f, 0.333333343267f, 0.333333343267f}, {0.239495798945f, 0.337254911661f, 0.337254911661f}, {0.243697479367f, 0.345098048449f, 0.345098048449f}, {0.247899159789f, 0.349019616842f, 0.349019616842f}, {0.252100855112f, 0.360784322023f, 0.360784322023f}, {0.256302535534f, 0.368627458811f, 0.368627458811f}, {0.260504215956f, 0.372549027205f, 0.372549027205f}, {0.264705896378f, 0.380392163992f, 0.380392163992f}, {0.268907576799f, 0.384313732386f, 0.384313732386f}, {0.273109257221f, 0.388235300779f, 0.388235300779f}, {0.277310937643f, 0.396078437567f, 0.396078437567f}, {0.281512618065f, 0.40000000596f, 0.40000000596f}, {0.285714298487f, 0.407843142748f, 0.407843142748f}, {0.289915978909f, 0.411764711142f, 0.411764711142f}, {0.29411765933f, 0.423529416323f, 0.423529416323f}, {0.298319339752f, 0.43137255311f, 0.43137255311f}, {0.302521020174f, 0.435294121504f, 0.435294121504f}, {0.306722700596f, 0.443137258291f, 0.443137258291f}, {0.310924381018f, 0.447058826685f, 0.447058826685f}, {0.31512606144f, 0.450980395079f, 0.450980395079f}, {0.319327741861f, 0.458823531866f, 0.458823531866f}, {0.323529422283f, 0.46274510026f, 0.46274510026f}, {0.327731102705f, 0.470588237047f, 0.470588237047f}, {0.331932783127f, 0.474509805441f, 0.474509805441f}, {0.336134463549f, 0.482352942228f, 0.482352942228f}, {0.34033614397f, 0.486274510622f, 0.486274510622f}, {0.344537824392f, 0.494117647409f, 0.494117647409f}, {0.348739504814f, 0.498039215803f, 0.498039215803f}, {0.352941185236f, 0.501960813999f, 0.501960813999f}, {0.357142865658f, 0.509803950787f, 0.509803950787f}, {0.36134454608f, 0.51372551918f, 0.51372551918f}, {0.365546226501f, 0.521568655968f, 0.521568655968f}, {0.369747906923f, 0.525490224361f, 0.525490224361f}, {0.373949587345f, 0.533333361149f, 0.533333361149f}, {0.378151267767f, 0.54509806633f, 0.54509806633f}, {0.382352948189f, 0.549019634724f, 0.549019634724f}, {0.386554628611f, 0.552941203117f, 0.552941203117f}, {0.390756309032f, 0.560784339905f, 0.560784339905f}, {0.394957989454f, 0.564705908298f, 0.564705908298f}, {0.399159669876f, 0.572549045086f, 0.572549045086f}, {0.403361350298f, 0.57647061348f, 0.57647061348f}, {0.40756303072f, 0.584313750267f, 0.584313750267f}, {0.411764711142f, 0.588235318661f, 0.588235318661f}, {0.415966391563f, 0.596078455448f, 0.596078455448f}, {0.420168071985f, 0.600000023842f, 0.600000023842f}, {0.424369752407f, 0.607843160629f, 0.607843160629f}, {0.428571432829f, 0.611764729023f, 0.611764729023f}, {0.432773113251f, 0.615686297417f, 0.615686297417f}, {0.436974793673f, 0.623529434204f, 0.623529434204f}, {0.441176474094f, 0.627451002598f, 0.627451002598f}, {0.445378154516f, 0.635294139385f, 0.635294139385f}, {0.449579834938f, 0.639215707779f, 0.639215707779f}, {0.45378151536f, 0.647058844566f, 0.647058844566f}, {0.457983195782f, 0.65098041296f, 0.65098041296f}, {0.462184876204f, 0.662745118141f, 0.662745118141f}, {0.466386556625f, 0.666666686535f, 0.666666686535f}, {0.470588237047f, 0.674509823322f, 0.674509823322f}, {0.474789917469f, 0.678431391716f, 0.678431391716f}, {0.478991597891f, 0.686274528503f, 0.686274528503f}, {0.483193278313f, 0.690196096897f, 0.690196096897f}, {0.487394958735f, 0.698039233685f, 0.698039233685f}, {0.491596639156f, 0.701960802078f, 0.701960802078f}, {0.495798319578f, 0.709803938866f, 0.709803938866f}, {0.5f, 0.713725507259f, 0.713725507259f}, {0.504201710224f, 0.72549021244f, 0.72549021244f}, {0.508403360844f, 0.729411780834f, 0.729411780834f}, {0.512605071068f, 0.737254917622f, 0.737254917622f}, {0.516806721687f, 0.741176486015f, 0.741176486015f}, {0.521008431911f, 0.749019622803f, 0.749019622803f}, {0.525210082531f, 0.752941191196f, 0.752941191196f}, {0.529411792755f, 0.760784327984f, 0.760784327984f}, {0.533613443375f, 0.764705896378f, 0.764705896378f}, {0.537815153599f, 0.772549033165f, 0.772549033165f}, {0.542016804218f, 0.776470601559f, 0.776470601559f}, {0.546218514442f, 0.78823530674f, 0.78823530674f}, {0.550420165062f, 0.792156875134f, 0.792156875134f}, {0.554621875286f, 0.800000011921f, 0.800000011921f}, {0.558823525906f, 0.803921580315f, 0.803921580315f}, {0.56302523613f, 0.811764717102f, 0.811764717102f}, {0.567226886749f, 0.815686285496f, 0.815686285496f}, {0.571428596973f, 0.823529422283f, 0.823529422283f}, {0.575630247593f, 0.827450990677f, 0.827450990677f}, {0.579831957817f, 0.831372559071f, 0.831372559071f}, {0.584033608437f, 0.839215695858f, 0.839215695858f}, {0.588235318661f, 0.843137264252f, 0.843137264252f}, {0.59243696928f, 0.850980401039f, 0.850980401039f}, {0.596638679504f, 0.854901969433f, 0.854901969433f}, {0.600840330124f, 0.86274510622f, 0.86274510622f}, {0.605042040348f, 0.866666674614f, 0.866666674614f}, {0.609243690968f, 0.874509811401f, 0.874509811401f}, {0.613445401192f, 0.878431379795f, 0.878431379795f}, {0.617647051811f, 0.886274516582f, 0.886274516582f}, {0.621848762035f, 0.890196084976f, 0.890196084976f}, {0.626050412655f, 0.89411765337f, 0.89411765337f}, {0.630252122879f, 0.905882358551f, 0.905882358551f}, {0.634453773499f, 0.913725495338f, 0.913725495338f}, {0.638655483723f, 0.917647063732f, 0.917647063732f}, {0.642857134342f, 0.92549020052f, 0.92549020052f}, {0.647058844566f, 0.929411768913f, 0.929411768913f}, {0.651260495186f, 0.937254905701f, 0.937254905701f}, {0.65546220541f, 0.941176474094f, 0.941176474094f}, {0.65966385603f, 0.945098042488f, 0.945098042488f}, {0.663865566254f, 0.952941179276f, 0.952941179276f}, {0.668067216873f, 0.956862747669f, 0.956862747669f}, {0.672268927097f, 0.964705884457f, 0.964705884457f}, {0.676470577717f, 0.96862745285f, 0.96862745285f}, {0.680672287941f, 0.976470589638f, 0.976470589638f}, {0.68487393856f, 0.980392158031f, 0.980392158031f}, {0.689075648785f, 0.988235294819f, 0.988235294819f}, {0.693277299404f, 0.992156863213f, 0.992156863213f}, {0.697479009628f, 1.0f, 1.0f}, {0.701680660248f, 1.0f, 1.0f}, {0.705882370472f, 1.0f, 1.0f}, {0.710084021091f, 1.0f, 1.0f}, {0.714285731316f, 1.0f, 1.0f}, {0.718487381935f, 1.0f, 1.0f}, {0.722689092159f, 1.0f, 1.0f}, {0.726890742779f, 1.0f, 1.0f}, {0.731092453003f, 1.0f, 1.0f}, {0.735294103622f, 1.0f, 1.0f}, {0.739495813847f, 1.0f, 1.0f}, {0.743697464466f, 1.0f, 1.0f}, {0.74789917469f, 1.0f, 1.0f}, {0.75210082531f, 1.0f, 1.0f}, {0.756302535534f, 1.0f, 1.0f}, {0.760504186153f, 1.0f, 1.0f}, {0.764705896378f, 1.0f, 1.0f}, {0.768907546997f, 1.0f, 1.0f}, {0.773109257221f, 1.0f, 1.0f}, {0.777310907841f, 1.0f, 1.0f}, {0.781512618065f, 1.0f, 1.0f}, {0.785714268684f, 1.0f, 1.0f}, {0.789915978909f, 1.0f, 1.0f}, {0.794117629528f, 1.0f, 1.0f}, {0.798319339752f, 1.0f, 1.0f}, {0.802520990372f, 1.0f, 1.0f}, {0.806722700596f, 1.0f, 1.0f}, {0.810924351215f, 1.0f, 1.0f}, {0.81512606144f, 1.0f, 1.0f}, {0.819327712059f, 1.0f, 1.0f}, {0.823529422283f, 1.0f, 1.0f}, {0.827731072903f, 1.0f, 1.0f}, {0.831932783127f, 1.0f, 1.0f}, {0.836134433746f, 1.0f, 1.0f}, {0.84033614397f, 1.0f, 1.0f}, {0.84453779459f, 1.0f, 1.0f}, {0.848739504814f, 1.0f, 1.0f}, {0.852941155434f, 1.0f, 1.0f}, {0.857142865658f, 1.0f, 1.0f}, {0.861344516277f, 1.0f, 1.0f}, {0.865546226501f, 1.0f, 1.0f}, {0.869747877121f, 1.0f, 1.0f}, {0.873949587345f, 1.0f, 1.0f}, {0.878151237965f, 1.0f, 1.0f}, {0.882352948189f, 1.0f, 1.0f}, {0.886554598808f, 1.0f, 1.0f}, {0.890756309032f, 1.0f, 1.0f}, {0.894957959652f, 1.0f, 1.0f}, {0.899159669876f, 1.0f, 1.0f}, {0.903361320496f, 1.0f, 1.0f}, {0.90756303072f, 1.0f, 1.0f}, {0.911764681339f, 1.0f, 1.0f}, {0.915966391563f, 1.0f, 1.0f}, {0.920168042183f, 1.0f, 1.0f}, {0.924369752407f, 1.0f, 1.0f}, {0.928571403027f, 1.0f, 1.0f}, {0.932773113251f, 1.0f, 1.0f}, {0.93697476387f, 1.0f, 1.0f}, {0.941176474094f, 1.0f, 1.0f}, {0.945378124714f, 1.0f, 1.0f}, {0.949579834938f, 1.0f, 1.0f}, {0.953781485558f, 1.0f, 1.0f}, {0.957983195782f, 1.0f, 1.0f}, {0.962184846401f, 1.0f, 1.0f}, {0.966386556625f, 1.0f, 1.0f}, {0.970588207245f, 1.0f, 1.0f}, {0.974789917469f, 1.0f, 1.0f}, {0.978991568089f, 1.0f, 1.0f}, {0.983193278313f, 1.0f, 1.0f}, {0.987394928932f, 1.0f, 1.0f}, {0.991596639156f, 1.0f, 1.0f}, {0.995798289776f, 1.0f, 1.0f}, {1.0f, 1.0f, 1.0f}}, { // green {0.0f, 0.0f, 0.0f}, {0.00420168088749f, 0.0f, 0.0f}, {0.00840336177498f, 0.0f, 0.0f}, {0.0126050421968f, 0.0f, 0.0f}, {0.01680672355f, 0.0f, 0.0f}, {0.0210084039718f, 0.0f, 0.0f}, {0.0252100843936f, 0.0f, 0.0f}, {0.0294117648154f, 0.0f, 0.0f}, {0.0336134470999f, 0.0f, 0.0f}, {0.0378151275218f, 0.0f, 0.0f}, {0.0420168079436f, 0.0f, 0.0f}, {0.0462184883654f, 0.0f, 0.0f}, {0.0504201687872f, 0.0f, 0.0f}, {0.0546218492091f, 0.0f, 0.0f}, {0.0588235296309f, 0.0f, 0.0f}, {0.063025213778f, 0.0f, 0.0f}, {0.0672268941998f, 0.0f, 0.0f}, {0.0714285746217f, 0.0f, 0.0f}, {0.0756302550435f, 0.0f, 0.0f}, {0.0798319354653f, 0.0f, 0.0f}, {0.0840336158872f, 0.0f, 0.0f}, {0.088235296309f, 0.0f, 0.0f}, {0.0924369767308f, 0.0f, 0.0f}, {0.0966386571527f, 0.0f, 0.0f}, {0.100840337574f, 0.0f, 0.0f}, {0.105042017996f, 0.0f, 0.0f}, {0.109243698418f, 0.0f, 0.0f}, {0.11344537884f, 0.0f, 0.0f}, {0.117647059262f, 0.0f, 0.0f}, {0.121848739684f, 0.0f, 0.0f}, {0.126050427556f, 0.0f, 0.0f}, {0.130252107978f, 0.0f, 0.0f}, {0.1344537884f, 0.0f, 0.0f}, {0.138655468822f, 0.0f, 0.0f}, {0.142857149243f, 0.0f, 0.0f}, {0.147058829665f, 0.0f, 0.0f}, {0.151260510087f, 0.0f, 0.0f}, {0.155462190509f, 0.0f, 0.0f}, {0.159663870931f, 0.0f, 0.0f}, {0.163865551353f, 0.0f, 0.0f}, {0.168067231774f, 0.0f, 0.0f}, {0.172268912196f, 0.0f, 0.0f}, {0.176470592618f, 0.0f, 0.0f}, {0.18067227304f, 0.0f, 0.0f}, {0.184873953462f, 0.0f, 0.0f}, {0.189075633883f, 0.0f, 0.0f}, {0.193277314305f, 0.0f, 0.0f}, {0.197478994727f, 0.0f, 0.0f}, {0.201680675149f, 0.0f, 0.0f}, {0.205882355571f, 0.0f, 0.0f}, {0.210084035993f, 0.0f, 0.0f}, {0.214285716414f, 0.0f, 0.0f}, {0.218487396836f, 0.0f, 0.0f}, {0.222689077258f, 0.0f, 0.0f}, {0.22689075768f, 0.0f, 0.0f}, {0.231092438102f, 0.0f, 0.0f}, {0.235294118524f, 0.0f, 0.0f}, {0.239495798945f, 0.0f, 0.0f}, {0.243697479367f, 0.0f, 0.0f}, {0.247899159789f, 0.0f, 0.0f}, {0.252100855112f, 0.0f, 0.0f}, {0.256302535534f, 0.0f, 0.0f}, {0.260504215956f, 0.0f, 0.0f}, {0.264705896378f, 0.0f, 0.0f}, {0.268907576799f, 0.0f, 0.0f}, {0.273109257221f, 0.0f, 0.0f}, {0.277310937643f, 0.0f, 0.0f}, {0.281512618065f, 0.0f, 0.0f}, {0.285714298487f, 0.0f, 0.0f}, {0.289915978909f, 0.0f, 0.0f}, {0.29411765933f, 0.0f, 0.0f}, {0.298319339752f, 0.0f, 0.0f}, {0.302521020174f, 0.0f, 0.0f}, {0.306722700596f, 0.0f, 0.0f}, {0.310924381018f, 0.0f, 0.0f}, {0.31512606144f, 0.0f, 0.0f}, {0.319327741861f, 0.0f, 0.0f}, {0.323529422283f, 0.0f, 0.0f}, {0.327731102705f, 0.0f, 0.0f}, {0.331932783127f, 0.0f, 0.0f}, {0.336134463549f, 0.0f, 0.0f}, {0.34033614397f, 0.0f, 0.0f}, {0.344537824392f, 0.0f, 0.0f}, {0.348739504814f, 0.0f, 0.0f}, {0.352941185236f, 0.0f, 0.0f}, {0.357142865658f, 0.0f, 0.0f}, {0.36134454608f, 0.0f, 0.0f}, {0.365546226501f, 0.0f, 0.0f}, {0.369747906923f, 0.0f, 0.0f}, {0.373949587345f, 0.0f, 0.0f}, {0.378151267767f, 0.0f, 0.0f}, {0.382352948189f, 0.0f, 0.0f}, {0.386554628611f, 0.0f, 0.0f}, {0.390756309032f, 0.0f, 0.0f}, {0.394957989454f, 0.0f, 0.0f}, {0.399159669876f, 0.0f, 0.0f}, {0.403361350298f, 0.0f, 0.0f}, {0.40756303072f, 0.0f, 0.0f}, {0.411764711142f, 0.0f, 0.0f}, {0.415966391563f, 0.0f, 0.0f}, {0.420168071985f, 0.0f, 0.0f}, {0.424369752407f, 0.0f, 0.0f}, {0.428571432829f, 0.0f, 0.0f}, {0.432773113251f, 0.0f, 0.0f}, {0.436974793673f, 0.0f, 0.0f}, {0.441176474094f, 0.0f, 0.0f}, {0.445378154516f, 0.0f, 0.0f}, {0.449579834938f, 0.0f, 0.0f}, {0.45378151536f, 0.0f, 0.0f}, {0.457983195782f, 0.0f, 0.0f}, {0.462184876204f, 0.0f, 0.0f}, {0.466386556625f, 0.0f, 0.0f}, {0.470588237047f, 0.0f, 0.0f}, {0.474789917469f, 0.0f, 0.0f}, {0.478991597891f, 0.00392156885937f, 0.00392156885937f}, {0.483193278313f, 0.0117647061124f, 0.0117647061124f}, {0.487394958735f, 0.0196078438312f, 0.0196078438312f}, {0.491596639156f, 0.0274509806186f, 0.0274509806186f}, {0.495798319578f, 0.0352941192687f, 0.0352941192687f}, {0.5f, 0.0431372560561f, 0.0431372560561f}, {0.504201710224f, 0.0588235296309f, 0.0588235296309f}, {0.508403360844f, 0.0666666701436f, 0.0666666701436f}, {0.512605071068f, 0.0705882385373f, 0.0705882385373f}, {0.516806721687f, 0.0784313753247f, 0.0784313753247f}, {0.521008431911f, 0.0862745121121f, 0.0862745121121f}, {0.525210082531f, 0.0941176488996f, 0.0941176488996f}, {0.529411792755f, 0.101960785687f, 0.101960785687f}, {0.533613443375f, 0.109803922474f, 0.109803922474f}, {0.537815153599f, 0.117647059262f, 0.117647059262f}, {0.542016804218f, 0.1254902035f, 0.1254902035f}, {0.546218514442f, 0.137254908681f, 0.137254908681f}, {0.550420165062f, 0.145098045468f, 0.145098045468f}, {0.554621875286f, 0.152941182256f, 0.152941182256f}, {0.558823525906f, 0.160784319043f, 0.160784319043f}, {0.56302523613f, 0.168627455831f, 0.168627455831f}, {0.567226886749f, 0.176470592618f, 0.176470592618f}, {0.571428596973f, 0.184313729405f, 0.184313729405f}, {0.575630247593f, 0.192156866193f, 0.192156866193f}, {0.579831957817f, 0.20000000298f, 0.20000000298f}, {0.584033608437f, 0.203921571374f, 0.203921571374f}, {0.588235318661f, 0.211764708161f, 0.211764708161f}, {0.59243696928f, 0.219607844949f, 0.219607844949f}, {0.596638679504f, 0.227450981736f, 0.227450981736f}, {0.600840330124f, 0.235294118524f, 0.235294118524f}, {0.605042040348f, 0.243137255311f, 0.243137255311f}, {0.609243690968f, 0.250980407f, 0.250980407f}, {0.613445401192f, 0.258823543787f, 0.258823543787f}, {0.617647051811f, 0.266666680574f, 0.266666680574f}, {0.621848762035f, 0.270588248968f, 0.270588248968f}, {0.626050412655f, 0.278431385756f, 0.278431385756f}, {0.630252122879f, 0.29411765933f, 0.29411765933f}, {0.634453773499f, 0.301960796118f, 0.301960796118f}, {0.638655483723f, 0.309803932905f, 0.309803932905f}, {0.642857134342f, 0.317647069693f, 0.317647069693f}, {0.647058844566f, 0.32549020648f, 0.32549020648f}, {0.651260495186f, 0.333333343267f, 0.333333343267f}, {0.65546220541f, 0.337254911661f, 0.337254911661f}, {0.65966385603f, 0.345098048449f, 0.345098048449f}, {0.663865566254f, 0.352941185236f, 0.352941185236f}, {0.668067216873f, 0.360784322023f, 0.360784322023f}, {0.672268927097f, 0.368627458811f, 0.368627458811f}, {0.676470577717f, 0.376470595598f, 0.376470595598f}, {0.680672287941f, 0.384313732386f, 0.384313732386f}, {0.68487393856f, 0.392156869173f, 0.392156869173f}, {0.689075648785f, 0.40000000596f, 0.40000000596f}, {0.693277299404f, 0.403921574354f, 0.403921574354f}, {0.697479009628f, 0.411764711142f, 0.411764711142f}, {0.701680660248f, 0.419607847929f, 0.419607847929f}, {0.705882370472f, 0.427450984716f, 0.427450984716f}, {0.710084021091f, 0.435294121504f, 0.435294121504f}, {0.714285731316f, 0.450980395079f, 0.450980395079f}, {0.718487381935f, 0.458823531866f, 0.458823531866f}, {0.722689092159f, 0.466666668653f, 0.466666668653f}, {0.726890742779f, 0.470588237047f, 0.470588237047f}, {0.731092453003f, 0.478431373835f, 0.478431373835f}, {0.735294103622f, 0.486274510622f, 0.486274510622f}, {0.739495813847f, 0.494117647409f, 0.494117647409f}, {0.743697464466f, 0.501960813999f, 0.501960813999f}, {0.74789917469f, 0.509803950787f, 0.509803950787f}, {0.75210082531f, 0.517647087574f, 0.517647087574f}, {0.756302535534f, 0.533333361149f, 0.533333361149f}, {0.760504186153f, 0.537254929543f, 0.537254929543f}, {0.764705896378f, 0.54509806633f, 0.54509806633f}, {0.768907546997f, 0.552941203117f, 0.552941203117f}, {0.773109257221f, 0.560784339905f, 0.560784339905f}, {0.777310907841f, 0.568627476692f, 0.568627476692f}, {0.781512618065f, 0.57647061348f, 0.57647061348f}, {0.785714268684f, 0.584313750267f, 0.584313750267f}, {0.789915978909f, 0.592156887054f, 0.592156887054f}, {0.794117629528f, 0.600000023842f, 0.600000023842f}, {0.798319339752f, 0.611764729023f, 0.611764729023f}, {0.802520990372f, 0.61960786581f, 0.61960786581f}, {0.806722700596f, 0.627451002598f, 0.627451002598f}, {0.810924351215f, 0.635294139385f, 0.635294139385f}, {0.81512606144f, 0.643137276173f, 0.643137276173f}, {0.819327712059f, 0.65098041296f, 0.65098041296f}, {0.823529422283f, 0.658823549747f, 0.658823549747f}, {0.827731072903f, 0.666666686535f, 0.666666686535f}, {0.831932783127f, 0.670588254929f, 0.670588254929f}, {0.836134433746f, 0.678431391716f, 0.678431391716f}, {0.84033614397f, 0.686274528503f, 0.686274528503f}, {0.84453779459f, 0.694117665291f, 0.694117665291f}, {0.848739504814f, 0.701960802078f, 0.701960802078f}, {0.852941155434f, 0.709803938866f, 0.709803938866f}, {0.857142865658f, 0.717647075653f, 0.717647075653f}, {0.861344516277f, 0.72549021244f, 0.72549021244f}, {0.865546226501f, 0.733333349228f, 0.733333349228f}, {0.869747877121f, 0.737254917622f, 0.737254917622f}, {0.873949587345f, 0.745098054409f, 0.745098054409f}, {0.878151237965f, 0.752941191196f, 0.752941191196f}, {0.882352948189f, 0.768627464771f, 0.768627464771f}, {0.886554598808f, 0.776470601559f, 0.776470601559f}, {0.890756309032f, 0.784313738346f, 0.784313738346f}, {0.894957959652f, 0.792156875134f, 0.792156875134f}, {0.899159669876f, 0.800000011921f, 0.800000011921f}, {0.903361320496f, 0.803921580315f, 0.803921580315f}, {0.90756303072f, 0.811764717102f, 0.811764717102f}, {0.911764681339f, 0.819607853889f, 0.819607853889f}, {0.915966391563f, 0.827450990677f, 0.827450990677f}, {0.920168042183f, 0.835294127464f, 0.835294127464f}, {0.924369752407f, 0.843137264252f, 0.843137264252f}, {0.928571403027f, 0.850980401039f, 0.850980401039f}, {0.932773113251f, 0.858823537827f, 0.858823537827f}, {0.93697476387f, 0.866666674614f, 0.866666674614f}, {0.941176474094f, 0.870588243008f, 0.870588243008f}, {0.945378124714f, 0.878431379795f, 0.878431379795f}, {0.949579834938f, 0.886274516582f, 0.886274516582f}, {0.953781485558f, 0.89411765337f, 0.89411765337f}, {0.957983195782f, 0.901960790157f, 0.901960790157f}, {0.962184846401f, 0.909803926945f, 0.909803926945f}, {0.966386556625f, 0.92549020052f, 0.92549020052f}, {0.970588207245f, 0.933333337307f, 0.933333337307f}, {0.974789917469f, 0.937254905701f, 0.937254905701f}, {0.978991568089f, 0.945098042488f, 0.945098042488f}, {0.983193278313f, 0.952941179276f, 0.952941179276f}, {0.987394928932f, 0.960784316063f, 0.960784316063f}, {0.991596639156f, 0.96862745285f, 0.96862745285f}, {0.995798289776f, 0.976470589638f, 0.976470589638f}, {1.0f, 0.984313726425f, 0.984313726425f}}, { // blue {0.0f, 0.0f, 0.0f}, {0.00420168088749f, 0.0f, 0.0f}, {0.00840336177498f, 0.0f, 0.0f}, {0.0126050421968f, 0.0f, 0.0f}, {0.01680672355f, 0.0f, 0.0f}, {0.0210084039718f, 0.0f, 0.0f}, {0.0252100843936f, 0.0f, 0.0f}, {0.0294117648154f, 0.0f, 0.0f}, {0.0336134470999f, 0.0f, 0.0f}, {0.0378151275218f, 0.0f, 0.0f}, {0.0420168079436f, 0.0f, 0.0f}, {0.0462184883654f, 0.0f, 0.0f}, {0.0504201687872f, 0.0f, 0.0f}, {0.0546218492091f, 0.0f, 0.0f}, {0.0588235296309f, 0.0f, 0.0f}, {0.063025213778f, 0.0f, 0.0f}, {0.0672268941998f, 0.0f, 0.0f}, {0.0714285746217f, 0.0f, 0.0f}, {0.0756302550435f, 0.0f, 0.0f}, {0.0798319354653f, 0.0f, 0.0f}, {0.0840336158872f, 0.0f, 0.0f}, {0.088235296309f, 0.0f, 0.0f}, {0.0924369767308f, 0.0f, 0.0f}, {0.0966386571527f, 0.0f, 0.0f}, {0.100840337574f, 0.0f, 0.0f}, {0.105042017996f, 0.0f, 0.0f}, {0.109243698418f, 0.0f, 0.0f}, {0.11344537884f, 0.0f, 0.0f}, {0.117647059262f, 0.0f, 0.0f}, {0.121848739684f, 0.0f, 0.0f}, {0.126050427556f, 0.0f, 0.0f}, {0.130252107978f, 0.0f, 0.0f}, {0.1344537884f, 0.0f, 0.0f}, {0.138655468822f, 0.0f, 0.0f}, {0.142857149243f, 0.0f, 0.0f}, {0.147058829665f, 0.0f, 0.0f}, {0.151260510087f, 0.0f, 0.0f}, {0.155462190509f, 0.0f, 0.0f}, {0.159663870931f, 0.0f, 0.0f}, {0.163865551353f, 0.0f, 0.0f}, {0.168067231774f, 0.0f, 0.0f}, {0.172268912196f, 0.0f, 0.0f}, {0.176470592618f, 0.0f, 0.0f}, {0.18067227304f, 0.0f, 0.0f}, {0.184873953462f, 0.0f, 0.0f}, {0.189075633883f, 0.0f, 0.0f}, {0.193277314305f, 0.0f, 0.0f}, {0.197478994727f, 0.0f, 0.0f}, {0.201680675149f, 0.0f, 0.0f}, {0.205882355571f, 0.0f, 0.0f}, {0.210084035993f, 0.0f, 0.0f}, {0.214285716414f, 0.0f, 0.0f}, {0.218487396836f, 0.0f, 0.0f}, {0.222689077258f, 0.0f, 0.0f}, {0.22689075768f, 0.0f, 0.0f}, {0.231092438102f, 0.0f, 0.0f}, {0.235294118524f, 0.0f, 0.0f}, {0.239495798945f, 0.0f, 0.0f}, {0.243697479367f, 0.0f, 0.0f}, {0.247899159789f, 0.0f, 0.0f}, {0.252100855112f, 0.0f, 0.0f}, {0.256302535534f, 0.0f, 0.0f}, {0.260504215956f, 0.0f, 0.0f}, {0.264705896378f, 0.0f, 0.0f}, {0.268907576799f, 0.0f, 0.0f}, {0.273109257221f, 0.0f, 0.0f}, {0.277310937643f, 0.0f, 0.0f}, {0.281512618065f, 0.0f, 0.0f}, {0.285714298487f, 0.0f, 0.0f}, {0.289915978909f, 0.0f, 0.0f}, {0.29411765933f, 0.0f, 0.0f}, {0.298319339752f, 0.0f, 0.0f}, {0.302521020174f, 0.0f, 0.0f}, {0.306722700596f, 0.0f, 0.0f}, {0.310924381018f, 0.0f, 0.0f}, {0.31512606144f, 0.0f, 0.0f}, {0.319327741861f, 0.0f, 0.0f}, {0.323529422283f, 0.0f, 0.0f}, {0.327731102705f, 0.0f, 0.0f}, {0.331932783127f, 0.0f, 0.0f}, {0.336134463549f, 0.0f, 0.0f}, {0.34033614397f, 0.0f, 0.0f}, {0.344537824392f, 0.0f, 0.0f}, {0.348739504814f, 0.0f, 0.0f}, {0.352941185236f, 0.0f, 0.0f}, {0.357142865658f, 0.0f, 0.0f}, {0.36134454608f, 0.0f, 0.0f}, {0.365546226501f, 0.0f, 0.0f}, {0.369747906923f, 0.0f, 0.0f}, {0.373949587345f, 0.0f, 0.0f}, {0.378151267767f, 0.0f, 0.0f}, {0.382352948189f, 0.0f, 0.0f}, {0.386554628611f, 0.0f, 0.0f}, {0.390756309032f, 0.0f, 0.0f}, {0.394957989454f, 0.0f, 0.0f}, {0.399159669876f, 0.0f, 0.0f}, {0.403361350298f, 0.0f, 0.0f}, {0.40756303072f, 0.0f, 0.0f}, {0.411764711142f, 0.0f, 0.0f}, {0.415966391563f, 0.0f, 0.0f}, {0.420168071985f, 0.0f, 0.0f}, {0.424369752407f, 0.0f, 0.0f}, {0.428571432829f, 0.0f, 0.0f}, {0.432773113251f, 0.0f, 0.0f}, {0.436974793673f, 0.0f, 0.0f}, {0.441176474094f, 0.0f, 0.0f}, {0.445378154516f, 0.0f, 0.0f}, {0.449579834938f, 0.0f, 0.0f}, {0.45378151536f, 0.0f, 0.0f}, {0.457983195782f, 0.0f, 0.0f}, {0.462184876204f, 0.0f, 0.0f}, {0.466386556625f, 0.0f, 0.0f}, {0.470588237047f, 0.0f, 0.0f}, {0.474789917469f, 0.0f, 0.0f}, {0.478991597891f, 0.0f, 0.0f}, {0.483193278313f, 0.0f, 0.0f}, {0.487394958735f, 0.0f, 0.0f}, {0.491596639156f, 0.0f, 0.0f}, {0.495798319578f, 0.0f, 0.0f}, {0.5f, 0.0f, 0.0f}, {0.504201710224f, 0.0f, 0.0f}, {0.508403360844f, 0.0f, 0.0f}, {0.512605071068f, 0.0f, 0.0f}, {0.516806721687f, 0.0f, 0.0f}, {0.521008431911f, 0.0f, 0.0f}, {0.525210082531f, 0.0f, 0.0f}, {0.529411792755f, 0.0f, 0.0f}, {0.533613443375f, 0.0f, 0.0f}, {0.537815153599f, 0.0f, 0.0f}, {0.542016804218f, 0.0f, 0.0f}, {0.546218514442f, 0.0f, 0.0f}, {0.550420165062f, 0.0f, 0.0f}, {0.554621875286f, 0.0f, 0.0f}, {0.558823525906f, 0.0f, 0.0f}, {0.56302523613f, 0.0f, 0.0f}, {0.567226886749f, 0.0f, 0.0f}, {0.571428596973f, 0.0f, 0.0f}, {0.575630247593f, 0.0f, 0.0f}, {0.579831957817f, 0.0f, 0.0f}, {0.584033608437f, 0.0f, 0.0f}, {0.588235318661f, 0.0f, 0.0f}, {0.59243696928f, 0.0f, 0.0f}, {0.596638679504f, 0.0f, 0.0f}, {0.600840330124f, 0.0f, 0.0f}, {0.605042040348f, 0.0f, 0.0f}, {0.609243690968f, 0.0f, 0.0f}, {0.613445401192f, 0.0f, 0.0f}, {0.617647051811f, 0.0f, 0.0f}, {0.621848762035f, 0.0f, 0.0f}, {0.626050412655f, 0.0f, 0.0f}, {0.630252122879f, 0.0f, 0.0f}, {0.634453773499f, 0.0f, 0.0f}, {0.638655483723f, 0.0f, 0.0f}, {0.642857134342f, 0.0f, 0.0f}, {0.647058844566f, 0.0f, 0.0f}, {0.651260495186f, 0.0f, 0.0f}, {0.65546220541f, 0.0f, 0.0f}, {0.65966385603f, 0.0f, 0.0f}, {0.663865566254f, 0.0f, 0.0f}, {0.668067216873f, 0.0f, 0.0f}, {0.672268927097f, 0.0f, 0.0f}, {0.676470577717f, 0.0f, 0.0f}, {0.680672287941f, 0.0f, 0.0f}, {0.68487393856f, 0.0f, 0.0f}, {0.689075648785f, 0.0f, 0.0f}, {0.693277299404f, 0.0f, 0.0f}, {0.697479009628f, 0.0f, 0.0f}, {0.701680660248f, 0.0f, 0.0f}, {0.705882370472f, 0.0f, 0.0f}, {0.710084021091f, 0.0f, 0.0f}, {0.714285731316f, 0.0f, 0.0f}, {0.718487381935f, 0.0f, 0.0f}, {0.722689092159f, 0.0f, 0.0f}, {0.726890742779f, 0.0f, 0.0f}, {0.731092453003f, 0.0f, 0.0f}, {0.735294103622f, 0.0f, 0.0f}, {0.739495813847f, 0.0f, 0.0f}, {0.743697464466f, 0.0f, 0.0f}, {0.74789917469f, 0.0f, 0.0f}, {0.75210082531f, 0.0f, 0.0f}, {0.756302535534f, 0.0274509806186f, 0.0274509806186f}, {0.760504186153f, 0.0431372560561f, 0.0431372560561f}, {0.764705896378f, 0.0588235296309f, 0.0588235296309f}, {0.768907546997f, 0.074509806931f, 0.074509806931f}, {0.773109257221f, 0.0901960805058f, 0.0901960805058f}, {0.777310907841f, 0.105882354081f, 0.105882354081f}, {0.781512618065f, 0.121568627656f, 0.121568627656f}, {0.785714268684f, 0.137254908681f, 0.137254908681f}, {0.789915978909f, 0.152941182256f, 0.152941182256f}, {0.794117629528f, 0.168627455831f, 0.168627455831f}, {0.798319339752f, 0.20000000298f, 0.20000000298f}, {0.802520990372f, 0.211764708161f, 0.211764708161f}, {0.806722700596f, 0.227450981736f, 0.227450981736f}, {0.810924351215f, 0.243137255311f, 0.243137255311f}, {0.81512606144f, 0.258823543787f, 0.258823543787f}, {0.819327712059f, 0.274509817362f, 0.274509817362f}, {0.823529422283f, 0.290196090937f, 0.290196090937f}, {0.827731072903f, 0.305882364511f, 0.305882364511f}, {0.831932783127f, 0.321568638086f, 0.321568638086f}, {0.836134433746f, 0.337254911661f, 0.337254911661f}, {0.84033614397f, 0.352941185236f, 0.352941185236f}, {0.84453779459f, 0.368627458811f, 0.368627458811f}, {0.848739504814f, 0.384313732386f, 0.384313732386f}, {0.852941155434f, 0.40000000596f, 0.40000000596f}, {0.857142865658f, 0.411764711142f, 0.411764711142f}, {0.861344516277f, 0.427450984716f, 0.427450984716f}, {0.865546226501f, 0.443137258291f, 0.443137258291f}, {0.869747877121f, 0.458823531866f, 0.458823531866f}, {0.873949587345f, 0.474509805441f, 0.474509805441f}, {0.878151237965f, 0.490196079016f, 0.490196079016f}, {0.882352948189f, 0.521568655968f, 0.521568655968f}, {0.886554598808f, 0.537254929543f, 0.537254929543f}, {0.890756309032f, 0.552941203117f, 0.552941203117f}, {0.894957959652f, 0.568627476692f, 0.568627476692f}, {0.899159669876f, 0.584313750267f, 0.584313750267f}, {0.903361320496f, 0.600000023842f, 0.600000023842f}, {0.90756303072f, 0.611764729023f, 0.611764729023f}, {0.911764681339f, 0.627451002598f, 0.627451002598f}, {0.915966391563f, 0.643137276173f, 0.643137276173f}, {0.920168042183f, 0.658823549747f, 0.658823549747f}, {0.924369752407f, 0.674509823322f, 0.674509823322f}, {0.928571403027f, 0.690196096897f, 0.690196096897f}, {0.932773113251f, 0.705882370472f, 0.705882370472f}, {0.93697476387f, 0.721568644047f, 0.721568644047f}, {0.941176474094f, 0.737254917622f, 0.737254917622f}, {0.945378124714f, 0.752941191196f, 0.752941191196f}, {0.949579834938f, 0.768627464771f, 0.768627464771f}, {0.953781485558f, 0.784313738346f, 0.784313738346f}, {0.957983195782f, 0.800000011921f, 0.800000011921f}, {0.962184846401f, 0.811764717102f, 0.811764717102f}, {0.966386556625f, 0.843137264252f, 0.843137264252f}, {0.970588207245f, 0.858823537827f, 0.858823537827f}, {0.974789917469f, 0.874509811401f, 0.874509811401f}, {0.978991568089f, 0.890196084976f, 0.890196084976f}, {0.983193278313f, 0.905882358551f, 0.905882358551f}, {0.987394928932f, 0.921568632126f, 0.921568632126f}, {0.991596639156f, 0.937254905701f, 0.937254905701f}, {0.995798289776f, 0.952941179276f, 0.952941179276f}, {1.0f, 0.96862745285f, 0.96862745285f}}, { // alpha {0.0f, 1.0f, 1.0f}, {1.0f, 1.0f, 1.0f}} }; }
google/ExoPlayer
36,602
library/core/src/main/java/com/google/android/exoplayer2/video/DecoderVideoRenderer.java
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.video; import static com.google.android.exoplayer2.decoder.DecoderReuseEvaluation.DISCARD_REASON_DRM_SESSION_CHANGED; import static com.google.android.exoplayer2.decoder.DecoderReuseEvaluation.DISCARD_REASON_REUSE_NOT_IMPLEMENTED; import static com.google.android.exoplayer2.decoder.DecoderReuseEvaluation.REUSE_RESULT_NO; import static com.google.android.exoplayer2.source.SampleStream.FLAG_REQUIRE_FORMAT; import static com.google.android.exoplayer2.util.Util.msToUs; import static java.lang.Math.max; import static java.lang.annotation.ElementType.TYPE_USE; import android.os.Handler; import android.os.SystemClock; import android.view.Surface; import androidx.annotation.CallSuper; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import com.google.android.exoplayer2.BaseRenderer; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C.VideoOutputMode; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayer; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.FormatHolder; import com.google.android.exoplayer2.PlaybackException; import com.google.android.exoplayer2.PlayerMessage; import com.google.android.exoplayer2.decoder.CryptoConfig; import com.google.android.exoplayer2.decoder.Decoder; import com.google.android.exoplayer2.decoder.DecoderCounters; import com.google.android.exoplayer2.decoder.DecoderException; import com.google.android.exoplayer2.decoder.DecoderInputBuffer; import com.google.android.exoplayer2.decoder.DecoderReuseEvaluation; import com.google.android.exoplayer2.decoder.VideoDecoderOutputBuffer; import com.google.android.exoplayer2.drm.DrmSession; import com.google.android.exoplayer2.drm.DrmSession.DrmSessionException; import com.google.android.exoplayer2.source.SampleStream.ReadDataResult; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.util.TimedValueQueue; import com.google.android.exoplayer2.util.TraceUtil; import com.google.android.exoplayer2.video.VideoRendererEventListener.EventDispatcher; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Decodes and renders video using a {@link Decoder}. * * <p>This renderer accepts the following messages sent via {@link * ExoPlayer#createMessage(PlayerMessage.Target)} on the playback thread: * * <ul> * <li>Message with type {@link #MSG_SET_VIDEO_OUTPUT} to set the output surface. The message * payload should be the target {@link Surface} or {@link VideoDecoderOutputBufferRenderer}, * or null. Other non-null payloads have the effect of clearing the output. * <li>Message with type {@link #MSG_SET_VIDEO_FRAME_METADATA_LISTENER} to set a listener for * metadata associated with frames being rendered. The message payload should be the {@link * VideoFrameMetadataListener}, or null. * </ul> * * @deprecated com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which * contains the same ExoPlayer code). See <a * href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">the * migration guide</a> for more details, including a script to help with the migration. */ @Deprecated public abstract class DecoderVideoRenderer extends BaseRenderer { private static final String TAG = "DecoderVideoRenderer"; /** Decoder reinitialization states. */ @Documented @Retention(RetentionPolicy.SOURCE) @Target(TYPE_USE) @IntDef({ REINITIALIZATION_STATE_NONE, REINITIALIZATION_STATE_SIGNAL_END_OF_STREAM, REINITIALIZATION_STATE_WAIT_END_OF_STREAM }) private @interface ReinitializationState {} /** The decoder does not need to be re-initialized. */ private static final int REINITIALIZATION_STATE_NONE = 0; /** * The input format has changed in a way that requires the decoder to be re-initialized, but we * haven't yet signaled an end of stream to the existing decoder. We need to do so in order to * ensure that it outputs any remaining buffers before we release it. */ private static final int REINITIALIZATION_STATE_SIGNAL_END_OF_STREAM = 1; /** * The input format has changed in a way that requires the decoder to be re-initialized, and we've * signaled an end of stream to the existing decoder. We're waiting for the decoder to output an * end of stream signal to indicate that it has output any remaining buffers before we release it. */ private static final int REINITIALIZATION_STATE_WAIT_END_OF_STREAM = 2; private final long allowedJoiningTimeMs; private final int maxDroppedFramesToNotify; private final EventDispatcher eventDispatcher; private final TimedValueQueue<Format> formatQueue; private final DecoderInputBuffer flagsOnlyBuffer; private Format inputFormat; private Format outputFormat; @Nullable private Decoder< DecoderInputBuffer, ? extends VideoDecoderOutputBuffer, ? extends DecoderException> decoder; private DecoderInputBuffer inputBuffer; private VideoDecoderOutputBuffer outputBuffer; private @VideoOutputMode int outputMode; @Nullable private Object output; @Nullable private Surface outputSurface; @Nullable private VideoDecoderOutputBufferRenderer outputBufferRenderer; @Nullable private VideoFrameMetadataListener frameMetadataListener; @Nullable private DrmSession decoderDrmSession; @Nullable private DrmSession sourceDrmSession; private @ReinitializationState int decoderReinitializationState; private boolean decoderReceivedBuffers; private boolean renderedFirstFrameAfterReset; private boolean mayRenderFirstFrameAfterEnableIfNotStarted; private boolean renderedFirstFrameAfterEnable; private long initialPositionUs; private long joiningDeadlineMs; private boolean waitingForFirstSampleInFormat; private boolean inputStreamEnded; private boolean outputStreamEnded; @Nullable private VideoSize reportedVideoSize; private long droppedFrameAccumulationStartTimeMs; private int droppedFrames; private int consecutiveDroppedFrameCount; private int buffersInCodecCount; private long lastRenderTimeUs; private long outputStreamOffsetUs; /** Decoder event counters used for debugging purposes. */ protected DecoderCounters decoderCounters; /** * @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer * can attempt to seamlessly join an ongoing playback. * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be * null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. * @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between * invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}. */ protected DecoderVideoRenderer( long allowedJoiningTimeMs, @Nullable Handler eventHandler, @Nullable VideoRendererEventListener eventListener, int maxDroppedFramesToNotify) { super(C.TRACK_TYPE_VIDEO); this.allowedJoiningTimeMs = allowedJoiningTimeMs; this.maxDroppedFramesToNotify = maxDroppedFramesToNotify; joiningDeadlineMs = C.TIME_UNSET; clearReportedVideoSize(); formatQueue = new TimedValueQueue<>(); flagsOnlyBuffer = DecoderInputBuffer.newNoDataInstance(); eventDispatcher = new EventDispatcher(eventHandler, eventListener); decoderReinitializationState = REINITIALIZATION_STATE_NONE; outputMode = C.VIDEO_OUTPUT_MODE_NONE; } // BaseRenderer implementation. @Override public void render(long positionUs, long elapsedRealtimeUs) throws ExoPlaybackException { if (outputStreamEnded) { return; } if (inputFormat == null) { // We don't have a format yet, so try and read one. FormatHolder formatHolder = getFormatHolder(); flagsOnlyBuffer.clear(); @ReadDataResult int result = readSource(formatHolder, flagsOnlyBuffer, FLAG_REQUIRE_FORMAT); if (result == C.RESULT_FORMAT_READ) { onInputFormatChanged(formatHolder); } else if (result == C.RESULT_BUFFER_READ) { // End of stream read having not read a format. Assertions.checkState(flagsOnlyBuffer.isEndOfStream()); inputStreamEnded = true; outputStreamEnded = true; return; } else { // We still don't have a format and can't make progress without one. return; } } // If we don't have a decoder yet, we need to instantiate one. maybeInitDecoder(); if (decoder != null) { try { // Rendering loop. TraceUtil.beginSection("drainAndFeed"); while (drainOutputBuffer(positionUs, elapsedRealtimeUs)) {} while (feedInputBuffer()) {} TraceUtil.endSection(); } catch (DecoderException e) { Log.e(TAG, "Video codec error", e); eventDispatcher.videoCodecError(e); throw createRendererException(e, inputFormat, PlaybackException.ERROR_CODE_DECODING_FAILED); } decoderCounters.ensureUpdated(); } } @Override public boolean isEnded() { return outputStreamEnded; } @Override public boolean isReady() { if (inputFormat != null && (isSourceReady() || outputBuffer != null) && (renderedFirstFrameAfterReset || !hasOutput())) { // Ready. If we were joining then we've now joined, so clear the joining deadline. joiningDeadlineMs = C.TIME_UNSET; return true; } else if (joiningDeadlineMs == C.TIME_UNSET) { // Not joining. return false; } else if (SystemClock.elapsedRealtime() < joiningDeadlineMs) { // Joining and still within the joining deadline. return true; } else { // The joining deadline has been exceeded. Give up and clear the deadline. joiningDeadlineMs = C.TIME_UNSET; return false; } } // PlayerMessage.Target implementation. @Override public void handleMessage(@MessageType int messageType, @Nullable Object message) throws ExoPlaybackException { if (messageType == MSG_SET_VIDEO_OUTPUT) { setOutput(message); } else if (messageType == MSG_SET_VIDEO_FRAME_METADATA_LISTENER) { frameMetadataListener = (VideoFrameMetadataListener) message; } else { super.handleMessage(messageType, message); } } // Protected methods. @Override protected void onEnabled(boolean joining, boolean mayRenderStartOfStream) throws ExoPlaybackException { decoderCounters = new DecoderCounters(); eventDispatcher.enabled(decoderCounters); mayRenderFirstFrameAfterEnableIfNotStarted = mayRenderStartOfStream; renderedFirstFrameAfterEnable = false; } @Override protected void onPositionReset(long positionUs, boolean joining) throws ExoPlaybackException { inputStreamEnded = false; outputStreamEnded = false; clearRenderedFirstFrame(); initialPositionUs = C.TIME_UNSET; consecutiveDroppedFrameCount = 0; if (decoder != null) { flushDecoder(); } if (joining) { setJoiningDeadlineMs(); } else { joiningDeadlineMs = C.TIME_UNSET; } formatQueue.clear(); } @Override protected void onStarted() { droppedFrames = 0; droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime(); lastRenderTimeUs = msToUs(SystemClock.elapsedRealtime()); } @Override protected void onStopped() { joiningDeadlineMs = C.TIME_UNSET; maybeNotifyDroppedFrames(); } @Override protected void onDisabled() { inputFormat = null; clearReportedVideoSize(); clearRenderedFirstFrame(); try { setSourceDrmSession(null); releaseDecoder(); } finally { eventDispatcher.disabled(decoderCounters); } } @Override protected void onStreamChanged(Format[] formats, long startPositionUs, long offsetUs) throws ExoPlaybackException { // TODO: This shouldn't just update the output stream offset as long as there are still buffers // of the previous stream in the decoder. It should also make sure to render the first frame of // the next stream if the playback position reached the new stream. outputStreamOffsetUs = offsetUs; super.onStreamChanged(formats, startPositionUs, offsetUs); } /** * Flushes the decoder. * * @throws ExoPlaybackException If an error occurs reinitializing a decoder. */ @CallSuper protected void flushDecoder() throws ExoPlaybackException { buffersInCodecCount = 0; if (decoderReinitializationState != REINITIALIZATION_STATE_NONE) { releaseDecoder(); maybeInitDecoder(); } else { inputBuffer = null; if (outputBuffer != null) { outputBuffer.release(); outputBuffer = null; } decoder.flush(); decoderReceivedBuffers = false; } } /** Releases the decoder. */ @CallSuper protected void releaseDecoder() { inputBuffer = null; outputBuffer = null; decoderReinitializationState = REINITIALIZATION_STATE_NONE; decoderReceivedBuffers = false; buffersInCodecCount = 0; if (decoder != null) { decoderCounters.decoderReleaseCount++; decoder.release(); eventDispatcher.decoderReleased(decoder.getName()); decoder = null; } setDecoderDrmSession(null); } /** * Called when a new format is read from the upstream source. * * @param formatHolder A {@link FormatHolder} that holds the new {@link Format}. * @throws ExoPlaybackException If an error occurs (re-)initializing the decoder. */ @CallSuper protected void onInputFormatChanged(FormatHolder formatHolder) throws ExoPlaybackException { waitingForFirstSampleInFormat = true; Format newFormat = Assertions.checkNotNull(formatHolder.format); setSourceDrmSession(formatHolder.drmSession); Format oldFormat = inputFormat; inputFormat = newFormat; if (decoder == null) { maybeInitDecoder(); eventDispatcher.inputFormatChanged(inputFormat, /* decoderReuseEvaluation= */ null); return; } DecoderReuseEvaluation evaluation; if (sourceDrmSession != decoderDrmSession) { evaluation = new DecoderReuseEvaluation( decoder.getName(), oldFormat, newFormat, REUSE_RESULT_NO, DISCARD_REASON_DRM_SESSION_CHANGED); } else { evaluation = canReuseDecoder(decoder.getName(), oldFormat, newFormat); } if (evaluation.result == REUSE_RESULT_NO) { if (decoderReceivedBuffers) { // Signal end of stream and wait for any final output buffers before re-initialization. decoderReinitializationState = REINITIALIZATION_STATE_SIGNAL_END_OF_STREAM; } else { // There aren't any final output buffers, so release the decoder immediately. releaseDecoder(); maybeInitDecoder(); } } eventDispatcher.inputFormatChanged(inputFormat, evaluation); } /** * Called immediately before an input buffer is queued into the decoder. * * <p>The default implementation is a no-op. * * @param buffer The buffer that will be queued. */ protected void onQueueInputBuffer(DecoderInputBuffer buffer) { // Do nothing. } /** * Called when an output buffer is successfully processed. * * @param presentationTimeUs The timestamp associated with the output buffer. */ @CallSuper protected void onProcessedOutputBuffer(long presentationTimeUs) { buffersInCodecCount--; } /** * Returns whether the buffer being processed should be dropped. * * @param earlyUs The time until the buffer should be presented in microseconds. A negative value * indicates that the buffer is late. * @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds, * measured at the start of the current iteration of the rendering loop. */ protected boolean shouldDropOutputBuffer(long earlyUs, long elapsedRealtimeUs) { return isBufferLate(earlyUs); } /** * Returns whether to drop all buffers from the buffer being processed to the keyframe at or after * the current playback position, if possible. * * @param earlyUs The time until the current buffer should be presented in microseconds. A * negative value indicates that the buffer is late. * @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds, * measured at the start of the current iteration of the rendering loop. */ protected boolean shouldDropBuffersToKeyframe(long earlyUs, long elapsedRealtimeUs) { return isBufferVeryLate(earlyUs); } /** * Returns whether to force rendering an output buffer. * * @param earlyUs The time until the current buffer should be presented in microseconds. A * negative value indicates that the buffer is late. * @param elapsedSinceLastRenderUs The elapsed time since the last output buffer was rendered, in * microseconds. * @return Returns whether to force rendering an output buffer. */ protected boolean shouldForceRenderOutputBuffer(long earlyUs, long elapsedSinceLastRenderUs) { return isBufferLate(earlyUs) && elapsedSinceLastRenderUs > 100000; } /** * Skips the specified output buffer and releases it. * * @param outputBuffer The output buffer to skip. */ protected void skipOutputBuffer(VideoDecoderOutputBuffer outputBuffer) { decoderCounters.skippedOutputBufferCount++; outputBuffer.release(); } /** * Drops the specified output buffer and releases it. * * @param outputBuffer The output buffer to drop. */ protected void dropOutputBuffer(VideoDecoderOutputBuffer outputBuffer) { updateDroppedBufferCounters( /* droppedInputBufferCount= */ 0, /* droppedDecoderBufferCount= */ 1); outputBuffer.release(); } /** * Drops frames from the current output buffer to the next keyframe at or before the playback * position. If no such keyframe exists, as the playback position is inside the same group of * pictures as the buffer being processed, returns {@code false}. Returns {@code true} otherwise. * * @param positionUs The current playback position, in microseconds. * @return Whether any buffers were dropped. * @throws ExoPlaybackException If an error occurs flushing the decoder. */ protected boolean maybeDropBuffersToKeyframe(long positionUs) throws ExoPlaybackException { int droppedSourceBufferCount = skipSource(positionUs); if (droppedSourceBufferCount == 0) { return false; } decoderCounters.droppedToKeyframeCount++; // We dropped some buffers to catch up, so update the decoder counters and flush the decoder, // which releases all pending buffers buffers including the current output buffer. updateDroppedBufferCounters( droppedSourceBufferCount, /* droppedDecoderBufferCount= */ buffersInCodecCount); flushDecoder(); return true; } /** * Updates local counters and {@link #decoderCounters} to reflect that buffers were dropped. * * @param droppedInputBufferCount The number of buffers dropped from the source before being * passed to the decoder. * @param droppedDecoderBufferCount The number of buffers dropped after being passed to the * decoder. */ protected void updateDroppedBufferCounters( int droppedInputBufferCount, int droppedDecoderBufferCount) { decoderCounters.droppedInputBufferCount += droppedInputBufferCount; int totalDroppedBufferCount = droppedInputBufferCount + droppedDecoderBufferCount; decoderCounters.droppedBufferCount += totalDroppedBufferCount; droppedFrames += totalDroppedBufferCount; consecutiveDroppedFrameCount += totalDroppedBufferCount; decoderCounters.maxConsecutiveDroppedBufferCount = max(consecutiveDroppedFrameCount, decoderCounters.maxConsecutiveDroppedBufferCount); if (maxDroppedFramesToNotify > 0 && droppedFrames >= maxDroppedFramesToNotify) { maybeNotifyDroppedFrames(); } } /** * Creates a decoder for the given format. * * @param format The format for which a decoder is required. * @param cryptoConfig The {@link CryptoConfig} object required for decoding encrypted content. * May be null and can be ignored if decoder does not handle encrypted content. * @return The decoder. * @throws DecoderException If an error occurred creating a suitable decoder. */ protected abstract Decoder< DecoderInputBuffer, ? extends VideoDecoderOutputBuffer, ? extends DecoderException> createDecoder(Format format, @Nullable CryptoConfig cryptoConfig) throws DecoderException; /** * Renders the specified output buffer. * * <p>The implementation of this method takes ownership of the output buffer and is responsible * for calling {@link VideoDecoderOutputBuffer#release()} either immediately or in the future. * * @param outputBuffer {@link VideoDecoderOutputBuffer} to render. * @param presentationTimeUs Presentation time in microseconds. * @param outputFormat Output {@link Format}. * @throws DecoderException If an error occurs when rendering the output buffer. */ protected void renderOutputBuffer( VideoDecoderOutputBuffer outputBuffer, long presentationTimeUs, Format outputFormat) throws DecoderException { if (frameMetadataListener != null) { frameMetadataListener.onVideoFrameAboutToBeRendered( presentationTimeUs, System.nanoTime(), outputFormat, /* mediaFormat= */ null); } lastRenderTimeUs = msToUs(SystemClock.elapsedRealtime()); int bufferMode = outputBuffer.mode; boolean renderSurface = bufferMode == C.VIDEO_OUTPUT_MODE_SURFACE_YUV && outputSurface != null; boolean renderYuv = bufferMode == C.VIDEO_OUTPUT_MODE_YUV && outputBufferRenderer != null; if (!renderYuv && !renderSurface) { dropOutputBuffer(outputBuffer); } else { maybeNotifyVideoSizeChanged(outputBuffer.width, outputBuffer.height); if (renderYuv) { outputBufferRenderer.setOutputBuffer(outputBuffer); } else { renderOutputBufferToSurface(outputBuffer, outputSurface); } consecutiveDroppedFrameCount = 0; decoderCounters.renderedOutputBufferCount++; maybeNotifyRenderedFirstFrame(); } } /** * Renders the specified output buffer to the passed surface. * * <p>The implementation of this method takes ownership of the output buffer and is responsible * for calling {@link VideoDecoderOutputBuffer#release()} either immediately or in the future. * * @param outputBuffer {@link VideoDecoderOutputBuffer} to render. * @param surface Output {@link Surface}. * @throws DecoderException If an error occurs when rendering the output buffer. */ protected abstract void renderOutputBufferToSurface( VideoDecoderOutputBuffer outputBuffer, Surface surface) throws DecoderException; /** Sets the video output. */ protected final void setOutput(@Nullable Object output) { if (output instanceof Surface) { outputSurface = (Surface) output; outputBufferRenderer = null; outputMode = C.VIDEO_OUTPUT_MODE_SURFACE_YUV; } else if (output instanceof VideoDecoderOutputBufferRenderer) { outputSurface = null; outputBufferRenderer = (VideoDecoderOutputBufferRenderer) output; outputMode = C.VIDEO_OUTPUT_MODE_YUV; } else { // Handle unsupported outputs by clearing the output. output = null; outputSurface = null; outputBufferRenderer = null; outputMode = C.VIDEO_OUTPUT_MODE_NONE; } if (this.output != output) { this.output = output; if (output != null) { if (decoder != null) { setDecoderOutputMode(outputMode); } onOutputChanged(); } else { // The output has been removed. We leave the outputMode of the underlying decoder unchanged // in anticipation that a subsequent output will likely be of the same type. onOutputRemoved(); } } else if (output != null) { // The output is unchanged and non-null. onOutputReset(); } } /** * Sets output mode of the decoder. * * @param outputMode Output mode. */ protected abstract void setDecoderOutputMode(@VideoOutputMode int outputMode); /** * Evaluates whether the existing decoder can be reused for a new {@link Format}. * * <p>The default implementation does not allow decoder reuse. * * @param decoderName The name of the decoder. * @param oldFormat The previous format. * @param newFormat The new format. * @return The result of the evaluation. */ protected DecoderReuseEvaluation canReuseDecoder( String decoderName, Format oldFormat, Format newFormat) { return new DecoderReuseEvaluation( decoderName, oldFormat, newFormat, REUSE_RESULT_NO, DISCARD_REASON_REUSE_NOT_IMPLEMENTED); } // Internal methods. private void setSourceDrmSession(@Nullable DrmSession session) { DrmSession.replaceSession(sourceDrmSession, session); sourceDrmSession = session; } private void setDecoderDrmSession(@Nullable DrmSession session) { DrmSession.replaceSession(decoderDrmSession, session); decoderDrmSession = session; } private void maybeInitDecoder() throws ExoPlaybackException { if (decoder != null) { return; } setDecoderDrmSession(sourceDrmSession); CryptoConfig cryptoConfig = null; if (decoderDrmSession != null) { cryptoConfig = decoderDrmSession.getCryptoConfig(); if (cryptoConfig == null) { DrmSessionException drmError = decoderDrmSession.getError(); if (drmError != null) { // Continue for now. We may be able to avoid failure if a new input format causes the // session to be replaced without it having been used. } else { // The drm session isn't open yet. return; } } } try { long decoderInitializingTimestamp = SystemClock.elapsedRealtime(); decoder = createDecoder(inputFormat, cryptoConfig); setDecoderOutputMode(outputMode); long decoderInitializedTimestamp = SystemClock.elapsedRealtime(); eventDispatcher.decoderInitialized( decoder.getName(), decoderInitializedTimestamp, decoderInitializedTimestamp - decoderInitializingTimestamp); decoderCounters.decoderInitCount++; } catch (DecoderException e) { Log.e(TAG, "Video codec error", e); eventDispatcher.videoCodecError(e); throw createRendererException( e, inputFormat, PlaybackException.ERROR_CODE_DECODER_INIT_FAILED); } catch (OutOfMemoryError e) { throw createRendererException( e, inputFormat, PlaybackException.ERROR_CODE_DECODER_INIT_FAILED); } } private boolean feedInputBuffer() throws DecoderException, ExoPlaybackException { if (decoder == null || decoderReinitializationState == REINITIALIZATION_STATE_WAIT_END_OF_STREAM || inputStreamEnded) { // We need to reinitialize the decoder or the input stream has ended. return false; } if (inputBuffer == null) { inputBuffer = decoder.dequeueInputBuffer(); if (inputBuffer == null) { return false; } } if (decoderReinitializationState == REINITIALIZATION_STATE_SIGNAL_END_OF_STREAM) { inputBuffer.setFlags(C.BUFFER_FLAG_END_OF_STREAM); decoder.queueInputBuffer(inputBuffer); inputBuffer = null; decoderReinitializationState = REINITIALIZATION_STATE_WAIT_END_OF_STREAM; return false; } FormatHolder formatHolder = getFormatHolder(); switch (readSource(formatHolder, inputBuffer, /* readFlags= */ 0)) { case C.RESULT_NOTHING_READ: return false; case C.RESULT_FORMAT_READ: onInputFormatChanged(formatHolder); return true; case C.RESULT_BUFFER_READ: if (inputBuffer.isEndOfStream()) { inputStreamEnded = true; decoder.queueInputBuffer(inputBuffer); inputBuffer = null; return false; } if (waitingForFirstSampleInFormat) { formatQueue.add(inputBuffer.timeUs, inputFormat); waitingForFirstSampleInFormat = false; } inputBuffer.flip(); inputBuffer.format = inputFormat; onQueueInputBuffer(inputBuffer); decoder.queueInputBuffer(inputBuffer); buffersInCodecCount++; decoderReceivedBuffers = true; decoderCounters.queuedInputBufferCount++; inputBuffer = null; return true; default: throw new IllegalStateException(); } } /** * Attempts to dequeue an output buffer from the decoder and, if successful, passes it to {@link * #processOutputBuffer(long, long)}. * * @param positionUs The player's current position. * @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds, * measured at the start of the current iteration of the rendering loop. * @return Whether it may be possible to drain more output data. * @throws ExoPlaybackException If an error occurs draining the output buffer. */ private boolean drainOutputBuffer(long positionUs, long elapsedRealtimeUs) throws ExoPlaybackException, DecoderException { if (outputBuffer == null) { outputBuffer = decoder.dequeueOutputBuffer(); if (outputBuffer == null) { return false; } decoderCounters.skippedOutputBufferCount += outputBuffer.skippedOutputBufferCount; buffersInCodecCount -= outputBuffer.skippedOutputBufferCount; } if (outputBuffer.isEndOfStream()) { if (decoderReinitializationState == REINITIALIZATION_STATE_WAIT_END_OF_STREAM) { // We're waiting to re-initialize the decoder, and have now processed all final buffers. releaseDecoder(); maybeInitDecoder(); } else { outputBuffer.release(); outputBuffer = null; outputStreamEnded = true; } return false; } boolean processedOutputBuffer = processOutputBuffer(positionUs, elapsedRealtimeUs); if (processedOutputBuffer) { onProcessedOutputBuffer(outputBuffer.timeUs); outputBuffer = null; } return processedOutputBuffer; } /** * Processes {@link #outputBuffer} by rendering it, skipping it or doing nothing, and returns * whether it may be possible to process another output buffer. * * @param positionUs The player's current position. * @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds, * measured at the start of the current iteration of the rendering loop. * @return Whether it may be possible to drain another output buffer. * @throws ExoPlaybackException If an error occurs processing the output buffer. */ private boolean processOutputBuffer(long positionUs, long elapsedRealtimeUs) throws ExoPlaybackException, DecoderException { if (initialPositionUs == C.TIME_UNSET) { initialPositionUs = positionUs; } long earlyUs = outputBuffer.timeUs - positionUs; if (!hasOutput()) { // Skip frames in sync with playback, so we'll be at the right frame if the mode changes. if (isBufferLate(earlyUs)) { skipOutputBuffer(outputBuffer); return true; } return false; } long presentationTimeUs = outputBuffer.timeUs - outputStreamOffsetUs; Format format = formatQueue.pollFloor(presentationTimeUs); if (format != null) { outputFormat = format; } long elapsedRealtimeNowUs = msToUs(SystemClock.elapsedRealtime()); long elapsedSinceLastRenderUs = elapsedRealtimeNowUs - lastRenderTimeUs; boolean isStarted = getState() == STATE_STARTED; boolean shouldRenderFirstFrame = !renderedFirstFrameAfterEnable ? (isStarted || mayRenderFirstFrameAfterEnableIfNotStarted) : !renderedFirstFrameAfterReset; // TODO: We shouldn't force render while we are joining an ongoing playback. if (shouldRenderFirstFrame || (isStarted && shouldForceRenderOutputBuffer(earlyUs, elapsedSinceLastRenderUs))) { renderOutputBuffer(outputBuffer, presentationTimeUs, outputFormat); return true; } if (!isStarted || positionUs == initialPositionUs) { return false; } // TODO: Treat dropped buffers as skipped while we are joining an ongoing playback. if (shouldDropBuffersToKeyframe(earlyUs, elapsedRealtimeUs) && maybeDropBuffersToKeyframe(positionUs)) { return false; } else if (shouldDropOutputBuffer(earlyUs, elapsedRealtimeUs)) { dropOutputBuffer(outputBuffer); return true; } if (earlyUs < 30000) { renderOutputBuffer(outputBuffer, presentationTimeUs, outputFormat); return true; } return false; } private boolean hasOutput() { return outputMode != C.VIDEO_OUTPUT_MODE_NONE; } private void onOutputChanged() { // If we know the video size, report it again immediately. maybeRenotifyVideoSizeChanged(); // We haven't rendered to the new output yet. clearRenderedFirstFrame(); if (getState() == STATE_STARTED) { setJoiningDeadlineMs(); } } private void onOutputRemoved() { clearReportedVideoSize(); clearRenderedFirstFrame(); } private void onOutputReset() { // The output is unchanged and non-null. If we know the video size and/or have already // rendered to the output, report these again immediately. maybeRenotifyVideoSizeChanged(); maybeRenotifyRenderedFirstFrame(); } private void setJoiningDeadlineMs() { joiningDeadlineMs = allowedJoiningTimeMs > 0 ? (SystemClock.elapsedRealtime() + allowedJoiningTimeMs) : C.TIME_UNSET; } private void clearRenderedFirstFrame() { renderedFirstFrameAfterReset = false; } private void maybeNotifyRenderedFirstFrame() { renderedFirstFrameAfterEnable = true; if (!renderedFirstFrameAfterReset) { renderedFirstFrameAfterReset = true; eventDispatcher.renderedFirstFrame(output); } } private void maybeRenotifyRenderedFirstFrame() { if (renderedFirstFrameAfterReset) { eventDispatcher.renderedFirstFrame(output); } } private void clearReportedVideoSize() { reportedVideoSize = null; } private void maybeNotifyVideoSizeChanged(int width, int height) { if (reportedVideoSize == null || reportedVideoSize.width != width || reportedVideoSize.height != height) { reportedVideoSize = new VideoSize(width, height); eventDispatcher.videoSizeChanged(reportedVideoSize); } } private void maybeRenotifyVideoSizeChanged() { if (reportedVideoSize != null) { eventDispatcher.videoSizeChanged(reportedVideoSize); } } private void maybeNotifyDroppedFrames() { if (droppedFrames > 0) { long now = SystemClock.elapsedRealtime(); long elapsedMs = now - droppedFrameAccumulationStartTimeMs; eventDispatcher.droppedFrames(droppedFrames, elapsedMs); droppedFrames = 0; droppedFrameAccumulationStartTimeMs = now; } } private static boolean isBufferLate(long earlyUs) { // Class a buffer as late if it should have been presented more than 30 ms ago. return earlyUs < -30000; } private static boolean isBufferVeryLate(long earlyUs) { // Class a buffer as very late if it should have been presented more than 500 ms ago. return earlyUs < -500000; } }
apache/harmony
36,376
classlib/modules/regex/src/main/java/java/util/regex/AbstractCharClass.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Nikolay A. Kuznetsov */ package java.util.regex; import java.util.BitSet; import java.util.ListResourceBundle; /** * This class represents character classes, i.e. * sets of character either predefined or user defined. * * Note, this class represent token, not node, so being * constructed by lexer. * * @author Nikolay A. Kuznetsov */ abstract class AbstractCharClass extends SpecialToken { protected boolean alt; protected boolean altSurrogates; //Character.MAX_SURROGATE - Character.MIN_SURROGATE + 1 static int SURROGATE_CARDINALITY = 2048; BitSet lowHighSurrogates = new BitSet(SURROGATE_CARDINALITY); AbstractCharClass charClassWithoutSurrogates = null; AbstractCharClass charClassWithSurrogates = null; static PredefinedCharacterClasses charClasses = new PredefinedCharacterClasses(); /* * Indicates if this class may contain supplementary Unicode codepoints. * If this flag is specified it doesn't mean that this class contains * supplementary characters but may contain. */ protected boolean mayContainSupplCodepoints = false; /** * Returns true if this char class contains character specified; * * @param ch * character to check; */ abstract public boolean contains(int ch); /** * Returns BitSet representing this character class or <code>null</code> * if this character class does not have character representation; * * @return bitset */ protected BitSet getBits() { return null; } protected BitSet getLowHighSurrogates() { return lowHighSurrogates; } public boolean hasLowHighSurrogates() { return altSurrogates ? lowHighSurrogates.nextClearBit(0) < SURROGATE_CARDINALITY : lowHighSurrogates.nextSetBit(0) < SURROGATE_CARDINALITY; } public boolean mayContainSupplCodepoints() { return mayContainSupplCodepoints; } public int getType() { return SpecialToken.TOK_CHARCLASS; } public AbstractCharClass getInstance() { return this; } public AbstractCharClass getSurrogates() { if (charClassWithSurrogates == null) { final BitSet lHS = getLowHighSurrogates(); charClassWithSurrogates = new AbstractCharClass() { public boolean contains(int ch) { int index = ch - Character.MIN_SURROGATE; return ((index >= 0) && (index < AbstractCharClass.SURROGATE_CARDINALITY)) ? this.altSurrogates ^ lHS.get(index) : false; } }; charClassWithSurrogates.setNegative(this.altSurrogates); } return charClassWithSurrogates; } public AbstractCharClass getWithoutSurrogates() { if (charClassWithoutSurrogates == null) { final BitSet lHS = getLowHighSurrogates(); final AbstractCharClass thisClass = this; charClassWithoutSurrogates = new AbstractCharClass() { public boolean contains(int ch) { int index = ch - Character.MIN_SURROGATE; boolean containslHS = ((index >= 0) && (index < AbstractCharClass.SURROGATE_CARDINALITY)) ? this.altSurrogates ^ lHS.get(index) : false; return thisClass.contains(ch) && !containslHS; } }; charClassWithoutSurrogates.setNegative(isNegative()); charClassWithoutSurrogates.mayContainSupplCodepoints = mayContainSupplCodepoints; } return charClassWithoutSurrogates; } public boolean hasUCI() { return false; } /** * Sets this CharClass to negative form, i.e. if they will add some * characters and after that set this class to negative it will accept all * the characters except previously set ones. * * Although this method will not alternate all the already set characters, * just overall meaning of the class. * * @see #contains(int) * @see #intersect(CharClass) * @see #union(CharClass) */ public AbstractCharClass setNegative(boolean value) { if (alt ^ value) { alt = !alt; altSurrogates = !altSurrogates; } if (!mayContainSupplCodepoints) { mayContainSupplCodepoints = true; } return this; } public boolean isNegative() { return alt; } // ----------------------------------------------------------------- // Static methods and predefined classes // ----------------------------------------------------------------- public static boolean intersects(int ch1, int ch2) { return ch1 == ch2; } public static boolean intersects(AbstractCharClass cc, int ch) { return cc.contains(ch); } public static boolean intersects(AbstractCharClass cc1, AbstractCharClass cc2) { if (cc1.getBits() == null || cc2.getBits() == null) return true; return cc1.getBits().intersects(cc2.getBits()); } public static AbstractCharClass getPredefinedClass(String name, boolean negative) { return ((LazyCharClass) charClasses.getObject(name)).getValue(negative); } abstract static class LazyCharClass { AbstractCharClass posValue = null; AbstractCharClass negValue = null; public AbstractCharClass getValue(boolean negative) { if (!negative && posValue == null) { posValue = computeValue(); } else if (negative && negValue == null) { negValue = computeValue().setNegative(true); } if (!negative) return posValue; return negValue; } protected abstract AbstractCharClass computeValue(); } static class LazyDigit extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add('0', '9'); } } static class LazyNonDigit extends LazyDigit { protected AbstractCharClass computeValue() { AbstractCharClass chCl = super.computeValue().setNegative(true); chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazySpace extends LazyCharClass { protected AbstractCharClass computeValue() { /* 9-13 - \t\n\x0B\f\r; 32 - ' ' */ return new CharClass().add(9, 13).add(32); } } static class LazyNonSpace extends LazySpace { protected AbstractCharClass computeValue() { AbstractCharClass chCl = super.computeValue().setNegative(true); chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyWord extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add('a', 'z').add('A', 'Z').add('0', '9') .add('_'); } } static class LazyNonWord extends LazyWord { protected AbstractCharClass computeValue() { AbstractCharClass chCl = super.computeValue().setNegative(true); chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyLower extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add('a', 'z'); } } static class LazyUpper extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add('A', 'Z'); } } static class LazyASCII extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add(0x00, 0x7F); } } static class LazyAlpha extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add('a', 'z').add('A', 'Z'); } } static class LazyAlnum extends LazyAlpha { protected AbstractCharClass computeValue() { return ((CharClass) super.computeValue()).add('0', '9'); } } static class LazyPunct extends LazyCharClass { protected AbstractCharClass computeValue() { /* Punctuation !"#$%&'()*+,-./:;<=>?@ [\]^_` {|}~ */ return new CharClass().add(0x21, 0x40).add(0x5B, 0x60).add(0x7B, 0x7E); } } static class LazyGraph extends LazyAlnum { protected AbstractCharClass computeValue() { /* plus punctuation */ return ((CharClass) super.computeValue()).add(0x21, 0x40).add(0x5B, 0x60).add(0x7B, 0x7E); } } static class LazyPrint extends LazyGraph { protected AbstractCharClass computeValue() { return ((CharClass) super.computeValue()).add(0x20); } } static class LazyBlank extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add(' ').add('\t'); } } static class LazyCntrl extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add(0x00, 0x1F).add(0x7F); } } static class LazyXDigit extends LazyCharClass { protected AbstractCharClass computeValue() { return new CharClass().add('0', '9').add('a', 'f').add('A', 'F'); } } static class LazyRange extends LazyCharClass { int start, end; public LazyRange(int start, int end) { this.start = start; this.end = end; } public AbstractCharClass computeValue() { AbstractCharClass chCl = new CharClass().add(start, end); return chCl; } } static class LazySpecialsBlock extends LazyCharClass { public AbstractCharClass computeValue() { return new CharClass().add(0xFEFF, 0xFEFF).add(0xFFF0, 0xFFFD); } } static class LazyCategoryScope extends LazyCharClass { int category; boolean mayContainSupplCodepoints; boolean containsAllSurrogates; public LazyCategoryScope(int cat, boolean mayContainSupplCodepoints) { this.mayContainSupplCodepoints = mayContainSupplCodepoints; this.category = cat; } public LazyCategoryScope(int cat, boolean mayContainSupplCodepoints, boolean containsAllSurrogates) { this.containsAllSurrogates = containsAllSurrogates; this.mayContainSupplCodepoints = mayContainSupplCodepoints; this.category = cat; } protected AbstractCharClass computeValue() { AbstractCharClass chCl = new UnicodeCategoryScope(category); if (containsAllSurrogates) { chCl.lowHighSurrogates.set(0, SURROGATE_CARDINALITY); } chCl.mayContainSupplCodepoints = mayContainSupplCodepoints; return chCl; } } static class LazyCategory extends LazyCharClass { int category; boolean mayContainSupplCodepoints; boolean containsAllSurrogates; public LazyCategory(int cat, boolean mayContainSupplCodepoints) { this.mayContainSupplCodepoints = mayContainSupplCodepoints; this.category = cat; } public LazyCategory(int cat, boolean mayContainSupplCodepoints, boolean containsAllSurrogates) { this.containsAllSurrogates = containsAllSurrogates; this.mayContainSupplCodepoints = mayContainSupplCodepoints; this.category = cat; } protected AbstractCharClass computeValue() { AbstractCharClass chCl = new UnicodeCategory(category); if (containsAllSurrogates) { chCl.lowHighSurrogates.set(0, SURROGATE_CARDINALITY); } chCl.mayContainSupplCodepoints = mayContainSupplCodepoints;; return chCl; } } static class LazyJavaLowerCase extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isLowerCase(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaUpperCase extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isUpperCase(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaWhitespace extends LazyCharClass { protected AbstractCharClass computeValue() { return new AbstractCharClass() { public boolean contains(int ch) { return Character.isWhitespace(ch); } }; } } static class LazyJavaMirrored extends LazyCharClass { protected AbstractCharClass computeValue() { return new AbstractCharClass() { public boolean contains(int ch) { return Character.isMirrored(ch); } }; } } static class LazyJavaDefined extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isDefined(ch); } }; chCl.lowHighSurrogates.set(0, SURROGATE_CARDINALITY); chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaDigit extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isDigit(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaIdentifierIgnorable extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isIdentifierIgnorable(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaISOControl extends LazyCharClass { protected AbstractCharClass computeValue() { return new AbstractCharClass() { public boolean contains(int ch) { return Character.isISOControl(ch); } }; } } static class LazyJavaJavaIdentifierPart extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isJavaIdentifierPart(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaJavaIdentifierStart extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isJavaIdentifierStart(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaLetter extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isLetter(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaLetterOrDigit extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isLetterOrDigit(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaSpaceChar extends LazyCharClass { protected AbstractCharClass computeValue() { return new AbstractCharClass() { public boolean contains(int ch) { return Character.isSpaceChar(ch); } }; } } static class LazyJavaTitleCase extends LazyCharClass { protected AbstractCharClass computeValue() { return new AbstractCharClass() { public boolean contains(int ch) { return Character.isTitleCase(ch); } }; } } static class LazyJavaUnicodeIdentifierPart extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isUnicodeIdentifierPart(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } static class LazyJavaUnicodeIdentifierStart extends LazyCharClass { protected AbstractCharClass computeValue() { AbstractCharClass chCl = new AbstractCharClass() { public boolean contains(int ch) { return Character.isUnicodeIdentifierStart(ch); } }; chCl.mayContainSupplCodepoints = true; return chCl; } } /** * character classes generated from * http://www.unicode.org/reports/tr18/ * http://www.unicode.org/Public/4.1.0/ucd/Blocks.txt */ static final class PredefinedCharacterClasses extends ListResourceBundle { static LazyCharClass space = new LazySpace(); static LazyCharClass digit = new LazyDigit(); static final Object[][] contents = { { "Lower", new LazyLower() }, //$NON-NLS-1$ { "Upper", new LazyUpper() }, //$NON-NLS-1$ { "ASCII", new LazyASCII() }, //$NON-NLS-1$ { "Alpha", new LazyAlpha() }, //$NON-NLS-1$ { "Digit", digit }, //$NON-NLS-1$ { "Alnum", new LazyAlnum() }, //$NON-NLS-1$ { "Punct", new LazyPunct() }, //$NON-NLS-1$ { "Graph", new LazyGraph() }, //$NON-NLS-1$ { "Print", new LazyPrint() }, //$NON-NLS-1$ { "Blank", new LazyBlank() }, //$NON-NLS-1$ { "Cntrl", new LazyCntrl() }, //$NON-NLS-1$ { "XDigit", new LazyXDigit() }, //$NON-NLS-1$ { "javaLowerCase", new LazyJavaLowerCase() }, //$NON-NLS-1$ { "javaUpperCase", new LazyJavaUpperCase() }, //$NON-NLS-1$ { "javaWhitespace", new LazyJavaWhitespace() }, //$NON-NLS-1$ { "javaMirrored", new LazyJavaMirrored() }, //$NON-NLS-1$ { "javaDefined", new LazyJavaDefined() }, //$NON-NLS-1$ { "javaDigit", new LazyJavaDigit() }, //$NON-NLS-1$ { "javaIdentifierIgnorable", new LazyJavaIdentifierIgnorable() }, //$NON-NLS-1$ { "javaISOControl", new LazyJavaISOControl() }, //$NON-NLS-1$ { "javaJavaIdentifierPart", new LazyJavaJavaIdentifierPart() }, //$NON-NLS-1$ { "javaJavaIdentifierStart", new LazyJavaJavaIdentifierStart() }, //$NON-NLS-1$ { "javaLetter", new LazyJavaLetter() }, //$NON-NLS-1$ { "javaLetterOrDigit", new LazyJavaLetterOrDigit() }, //$NON-NLS-1$ { "javaSpaceChar", new LazyJavaSpaceChar() }, //$NON-NLS-1$ { "javaTitleCase", new LazyJavaTitleCase() }, //$NON-NLS-1$ { "javaUnicodeIdentifierPart", new LazyJavaUnicodeIdentifierPart() }, //$NON-NLS-1$ { "javaUnicodeIdentifierStart", new LazyJavaUnicodeIdentifierStart() }, //$NON-NLS-1$ { "Space", space }, //$NON-NLS-1$ { "w", new LazyWord() }, //$NON-NLS-1$ { "W", new LazyNonWord() }, //$NON-NLS-1$ { "s", space }, //$NON-NLS-1$ { "S", new LazyNonSpace() }, //$NON-NLS-1$ { "d", digit }, //$NON-NLS-1$ { "D", new LazyNonDigit() }, //$NON-NLS-1$ { "BasicLatin", new LazyRange(0x0000, 0x007F) }, //$NON-NLS-1$ { "Latin-1Supplement", new LazyRange(0x0080, 0x00FF) }, //$NON-NLS-1$ { "LatinExtended-A", new LazyRange(0x0100, 0x017F) }, //$NON-NLS-1$ { "LatinExtended-B", new LazyRange(0x0180, 0x024F) }, //$NON-NLS-1$ { "IPAExtensions", new LazyRange(0x0250, 0x02AF) }, //$NON-NLS-1$ { "SpacingModifierLetters", new LazyRange(0x02B0, 0x02FF) }, //$NON-NLS-1$ { "CombiningDiacriticalMarks", new LazyRange(0x0300, 0x036F) }, //$NON-NLS-1$ { "Greek", new LazyRange(0x0370, 0x03FF) }, //$NON-NLS-1$ { "Cyrillic", new LazyRange(0x0400, 0x04FF) }, //$NON-NLS-1$ { "CyrillicSupplement", new LazyRange(0x0500, 0x052F) }, //$NON-NLS-1$ { "Armenian", new LazyRange(0x0530, 0x058F) }, //$NON-NLS-1$ { "Hebrew", new LazyRange(0x0590, 0x05FF) }, //$NON-NLS-1$ { "Arabic", new LazyRange(0x0600, 0x06FF) }, //$NON-NLS-1$ { "Syriac", new LazyRange(0x0700, 0x074F) }, //$NON-NLS-1$ { "ArabicSupplement", new LazyRange(0x0750, 0x077F) }, //$NON-NLS-1$ { "Thaana", new LazyRange(0x0780, 0x07BF) }, //$NON-NLS-1$ { "Devanagari", new LazyRange(0x0900, 0x097F) }, //$NON-NLS-1$ { "Bengali", new LazyRange(0x0980, 0x09FF) }, //$NON-NLS-1$ { "Gurmukhi", new LazyRange(0x0A00, 0x0A7F) }, //$NON-NLS-1$ { "Gujarati", new LazyRange(0x0A80, 0x0AFF) }, //$NON-NLS-1$ { "Oriya", new LazyRange(0x0B00, 0x0B7F) }, //$NON-NLS-1$ { "Tamil", new LazyRange(0x0B80, 0x0BFF) }, //$NON-NLS-1$ { "Telugu", new LazyRange(0x0C00, 0x0C7F) }, //$NON-NLS-1$ { "Kannada", new LazyRange(0x0C80, 0x0CFF) }, //$NON-NLS-1$ { "Malayalam", new LazyRange(0x0D00, 0x0D7F) }, //$NON-NLS-1$ { "Sinhala", new LazyRange(0x0D80, 0x0DFF) }, //$NON-NLS-1$ { "Thai", new LazyRange(0x0E00, 0x0E7F) }, //$NON-NLS-1$ { "Lao", new LazyRange(0x0E80, 0x0EFF) }, //$NON-NLS-1$ { "Tibetan", new LazyRange(0x0F00, 0x0FFF) }, //$NON-NLS-1$ { "Myanmar", new LazyRange(0x1000, 0x109F) }, //$NON-NLS-1$ { "Georgian", new LazyRange(0x10A0, 0x10FF) }, //$NON-NLS-1$ { "HangulJamo", new LazyRange(0x1100, 0x11FF) }, //$NON-NLS-1$ { "Ethiopic", new LazyRange(0x1200, 0x137F) }, //$NON-NLS-1$ { "EthiopicSupplement", new LazyRange(0x1380, 0x139F) }, //$NON-NLS-1$ { "Cherokee", new LazyRange(0x13A0, 0x13FF) }, //$NON-NLS-1$ { "UnifiedCanadianAboriginalSyllabics", //$NON-NLS-1$ new LazyRange(0x1400, 0x167F) }, { "Ogham", new LazyRange(0x1680, 0x169F) }, //$NON-NLS-1$ { "Runic", new LazyRange(0x16A0, 0x16FF) }, //$NON-NLS-1$ { "Tagalog", new LazyRange(0x1700, 0x171F) }, //$NON-NLS-1$ { "Hanunoo", new LazyRange(0x1720, 0x173F) }, //$NON-NLS-1$ { "Buhid", new LazyRange(0x1740, 0x175F) }, //$NON-NLS-1$ { "Tagbanwa", new LazyRange(0x1760, 0x177F) }, //$NON-NLS-1$ { "Khmer", new LazyRange(0x1780, 0x17FF) }, //$NON-NLS-1$ { "Mongolian", new LazyRange(0x1800, 0x18AF) }, //$NON-NLS-1$ { "Limbu", new LazyRange(0x1900, 0x194F) }, //$NON-NLS-1$ { "TaiLe", new LazyRange(0x1950, 0x197F) }, //$NON-NLS-1$ { "NewTaiLue", new LazyRange(0x1980, 0x19DF) }, //$NON-NLS-1$ { "KhmerSymbols", new LazyRange(0x19E0, 0x19FF) }, //$NON-NLS-1$ { "Buginese", new LazyRange(0x1A00, 0x1A1F) }, //$NON-NLS-1$ { "PhoneticExtensions", new LazyRange(0x1D00, 0x1D7F) }, //$NON-NLS-1$ { "PhoneticExtensionsSupplement", new LazyRange(0x1D80, 0x1DBF) }, //$NON-NLS-1$ { "CombiningDiacriticalMarksSupplement", //$NON-NLS-1$ new LazyRange(0x1DC0, 0x1DFF) }, { "LatinExtendedAdditional", new LazyRange(0x1E00, 0x1EFF) }, //$NON-NLS-1$ { "GreekExtended", new LazyRange(0x1F00, 0x1FFF) }, //$NON-NLS-1$ { "GeneralPunctuation", new LazyRange(0x2000, 0x206F) }, //$NON-NLS-1$ { "SuperscriptsandSubscripts", new LazyRange(0x2070, 0x209F) }, //$NON-NLS-1$ { "CurrencySymbols", new LazyRange(0x20A0, 0x20CF) }, //$NON-NLS-1$ { "CombiningMarksforSymbols", new LazyRange(0x20D0, 0x20FF) }, //$NON-NLS-1$ { "LetterlikeSymbols", new LazyRange(0x2100, 0x214F) }, //$NON-NLS-1$ { "NumberForms", new LazyRange(0x2150, 0x218F) }, //$NON-NLS-1$ { "Arrows", new LazyRange(0x2190, 0x21FF) }, //$NON-NLS-1$ { "MathematicalOperators", new LazyRange(0x2200, 0x22FF) }, //$NON-NLS-1$ { "MiscellaneousTechnical", new LazyRange(0x2300, 0x23FF) }, //$NON-NLS-1$ { "ControlPictures", new LazyRange(0x2400, 0x243F) }, //$NON-NLS-1$ { "OpticalCharacterRecognition", new LazyRange(0x2440, 0x245F) }, //$NON-NLS-1$ { "EnclosedAlphanumerics", new LazyRange(0x2460, 0x24FF) }, //$NON-NLS-1$ { "BoxDrawing", new LazyRange(0x2500, 0x257F) }, //$NON-NLS-1$ { "BlockElements", new LazyRange(0x2580, 0x259F) }, //$NON-NLS-1$ { "GeometricShapes", new LazyRange(0x25A0, 0x25FF) }, //$NON-NLS-1$ { "MiscellaneousSymbols", new LazyRange(0x2600, 0x26FF) }, //$NON-NLS-1$ { "Dingbats", new LazyRange(0x2700, 0x27BF) }, //$NON-NLS-1$ { "MiscellaneousMathematicalSymbols-A", //$NON-NLS-1$ new LazyRange(0x27C0, 0x27EF) }, { "SupplementalArrows-A", new LazyRange(0x27F0, 0x27FF) }, //$NON-NLS-1$ { "BraillePatterns", new LazyRange(0x2800, 0x28FF) }, //$NON-NLS-1$ { "SupplementalArrows-B", new LazyRange(0x2900, 0x297F) }, //$NON-NLS-1$ { "MiscellaneousMathematicalSymbols-B", //$NON-NLS-1$ new LazyRange(0x2980, 0x29FF) }, { "SupplementalMathematicalOperators", //$NON-NLS-1$ new LazyRange(0x2A00, 0x2AFF) }, { "MiscellaneousSymbolsandArrows", //$NON-NLS-1$ new LazyRange(0x2B00, 0x2BFF) }, { "Glagolitic", new LazyRange(0x2C00, 0x2C5F) }, //$NON-NLS-1$ { "Coptic", new LazyRange(0x2C80, 0x2CFF) }, //$NON-NLS-1$ { "GeorgianSupplement", new LazyRange(0x2D00, 0x2D2F) }, //$NON-NLS-1$ { "Tifinagh", new LazyRange(0x2D30, 0x2D7F) }, //$NON-NLS-1$ { "EthiopicExtended", new LazyRange(0x2D80, 0x2DDF) }, //$NON-NLS-1$ { "SupplementalPunctuation", new LazyRange(0x2E00, 0x2E7F) }, //$NON-NLS-1$ { "CJKRadicalsSupplement", new LazyRange(0x2E80, 0x2EFF) }, //$NON-NLS-1$ { "KangxiRadicals", new LazyRange(0x2F00, 0x2FDF) }, //$NON-NLS-1$ { "IdeographicDescriptionCharacters", //$NON-NLS-1$ new LazyRange(0x2FF0, 0x2FFF) }, { "CJKSymbolsandPunctuation", new LazyRange(0x3000, 0x303F) }, //$NON-NLS-1$ { "Hiragana", new LazyRange(0x3040, 0x309F) }, //$NON-NLS-1$ { "Katakana", new LazyRange(0x30A0, 0x30FF) }, //$NON-NLS-1$ { "Bopomofo", new LazyRange(0x3100, 0x312F) }, //$NON-NLS-1$ { "HangulCompatibilityJamo", new LazyRange(0x3130, 0x318F) }, //$NON-NLS-1$ { "Kanbun", new LazyRange(0x3190, 0x319F) }, //$NON-NLS-1$ { "BopomofoExtended", new LazyRange(0x31A0, 0x31BF) }, //$NON-NLS-1$ { "CJKStrokes", new LazyRange(0x31C0, 0x31EF) }, //$NON-NLS-1$ { "KatakanaPhoneticExtensions", new LazyRange(0x31F0, 0x31FF) }, //$NON-NLS-1$ { "EnclosedCJKLettersandMonths", new LazyRange(0x3200, 0x32FF) }, //$NON-NLS-1$ { "CJKCompatibility", new LazyRange(0x3300, 0x33FF) }, //$NON-NLS-1$ { "CJKUnifiedIdeographsExtensionA", //$NON-NLS-1$ new LazyRange(0x3400, 0x4DB5) }, { "YijingHexagramSymbols", new LazyRange(0x4DC0, 0x4DFF) }, //$NON-NLS-1$ { "CJKUnifiedIdeographs", new LazyRange(0x4E00, 0x9FFF) }, //$NON-NLS-1$ { "YiSyllables", new LazyRange(0xA000, 0xA48F) }, //$NON-NLS-1$ { "YiRadicals", new LazyRange(0xA490, 0xA4CF) }, //$NON-NLS-1$ { "ModifierToneLetters", new LazyRange(0xA700, 0xA71F) }, //$NON-NLS-1$ { "SylotiNagri", new LazyRange(0xA800, 0xA82F) }, //$NON-NLS-1$ { "HangulSyllables", new LazyRange(0xAC00, 0xD7A3) }, //$NON-NLS-1$ { "HighSurrogates", new LazyRange(0xD800, 0xDB7F) }, //$NON-NLS-1$ { "HighPrivateUseSurrogates", new LazyRange(0xDB80, 0xDBFF) }, //$NON-NLS-1$ { "LowSurrogates", new LazyRange(0xDC00, 0xDFFF) }, //$NON-NLS-1$ { "PrivateUseArea", new LazyRange(0xE000, 0xF8FF) }, //$NON-NLS-1$ { "CJKCompatibilityIdeographs", new LazyRange(0xF900, 0xFAFF) }, //$NON-NLS-1$ { "AlphabeticPresentationForms", new LazyRange(0xFB00, 0xFB4F) }, //$NON-NLS-1$ { "ArabicPresentationForms-A", new LazyRange(0xFB50, 0xFDFF) }, //$NON-NLS-1$ { "VariationSelectors", new LazyRange(0xFE00, 0xFE0F) }, //$NON-NLS-1$ { "VerticalForms", new LazyRange(0xFE10, 0xFE1F) }, //$NON-NLS-1$ { "CombiningHalfMarks", new LazyRange(0xFE20, 0xFE2F) }, //$NON-NLS-1$ { "CJKCompatibilityForms", new LazyRange(0xFE30, 0xFE4F) }, //$NON-NLS-1$ { "SmallFormVariants", new LazyRange(0xFE50, 0xFE6F) }, //$NON-NLS-1$ { "ArabicPresentationForms-B", new LazyRange(0xFE70, 0xFEFF) }, //$NON-NLS-1$ { "HalfwidthandFullwidthForms", new LazyRange(0xFF00, 0xFFEF) }, //$NON-NLS-1$ { "all", new LazyRange(0x00, 0x10FFFF) }, //$NON-NLS-1$ { "Specials", new LazySpecialsBlock() }, //$NON-NLS-1$ { "Cn", new LazyCategory(Character.UNASSIGNED, true) }, { "IsL", new LazyCategoryScope(0x3E, true) }, { "Lu", new LazyCategory(Character.UPPERCASE_LETTER, true) }, { "Ll", new LazyCategory(Character.LOWERCASE_LETTER, true) }, { "Lt", new LazyCategory(Character.TITLECASE_LETTER, false) }, { "Lm", new LazyCategory(Character.MODIFIER_LETTER, false) }, { "Lo", new LazyCategory(Character.OTHER_LETTER, true) }, { "IsM", new LazyCategoryScope(0x1C0, true) }, { "Mn", new LazyCategory(Character.NON_SPACING_MARK, true) }, { "Me", new LazyCategory(Character.ENCLOSING_MARK, false) }, { "Mc", new LazyCategory(Character.COMBINING_SPACING_MARK, true) }, { "N", new LazyCategoryScope(0xE00, true) }, { "Nd", new LazyCategory(Character.DECIMAL_DIGIT_NUMBER, true) }, { "Nl", new LazyCategory(Character.LETTER_NUMBER, true) }, { "No", new LazyCategory(Character.OTHER_NUMBER, true) }, { "IsZ", new LazyCategoryScope(0x7000, false) }, { "Zs", new LazyCategory(Character.SPACE_SEPARATOR, false) }, { "Zl", new LazyCategory(Character.LINE_SEPARATOR, false) }, { "Zp", new LazyCategory(Character.PARAGRAPH_SEPARATOR, false) }, { "IsC", new LazyCategoryScope(0xF0000, true, true) }, { "Cc", new LazyCategory(Character.CONTROL, false) }, { "Cf", new LazyCategory(Character.FORMAT, true) }, { "Co", new LazyCategory(Character.PRIVATE_USE, true) }, { "Cs", new LazyCategory(Character.SURROGATE, false, true) }, {"IsP", new LazyCategoryScope((1 << Character.DASH_PUNCTUATION) | (1 << Character.START_PUNCTUATION) | (1 << Character.END_PUNCTUATION) | (1 << Character.CONNECTOR_PUNCTUATION) | (1 << Character.OTHER_PUNCTUATION) | (1 << Character.INITIAL_QUOTE_PUNCTUATION) | (1 << Character.FINAL_QUOTE_PUNCTUATION), true)}, { "Pd", new LazyCategory(Character.DASH_PUNCTUATION, false) }, { "Ps", new LazyCategory(Character.START_PUNCTUATION, false) }, { "Pe", new LazyCategory(Character.END_PUNCTUATION, false) }, { "Pc", new LazyCategory(Character.CONNECTOR_PUNCTUATION, false) }, { "Po", new LazyCategory(Character.OTHER_PUNCTUATION, true) }, { "IsS", new LazyCategoryScope(0x7E000000, true) }, { "Sm", new LazyCategory(Character.MATH_SYMBOL, true) }, { "Sc", new LazyCategory(Character.CURRENCY_SYMBOL, false) }, { "Sk", new LazyCategory(Character.MODIFIER_SYMBOL, false) }, { "So", new LazyCategory(Character.OTHER_SYMBOL, true) }, { "Pi", new LazyCategory(Character.INITIAL_QUOTE_PUNCTUATION, false) }, { "Pf", new LazyCategory(Character.FINAL_QUOTE_PUNCTUATION, false) } }; public Object[][] getContents() { return contents; } } }
googleapis/google-cloud-java
36,540
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/InstanceGroupManagersSetTargetPoolsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.compute.v1; /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest} */ public final class InstanceGroupManagersSetTargetPoolsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest) InstanceGroupManagersSetTargetPoolsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use InstanceGroupManagersSetTargetPoolsRequest.newBuilder() to construct. private InstanceGroupManagersSetTargetPoolsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InstanceGroupManagersSetTargetPoolsRequest() { fingerprint_ = ""; targetPools_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new InstanceGroupManagersSetTargetPoolsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InstanceGroupManagersSetTargetPoolsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InstanceGroupManagersSetTargetPoolsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest.class, com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest.Builder.class); } private int bitField0_; public static final int FINGERPRINT_FIELD_NUMBER = 234678500; @SuppressWarnings("serial") private volatile java.lang.Object fingerprint_ = ""; /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return Whether the fingerprint field is set. */ @java.lang.Override public boolean hasFingerprint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The fingerprint. */ @java.lang.Override public java.lang.String getFingerprint() { java.lang.Object ref = fingerprint_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); fingerprint_ = s; return s; } } /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The bytes for fingerprint. */ @java.lang.Override public com.google.protobuf.ByteString getFingerprintBytes() { java.lang.Object ref = fingerprint_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); fingerprint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TARGET_POOLS_FIELD_NUMBER = 336072617; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList targetPools_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @return A list containing the targetPools. */ public com.google.protobuf.ProtocolStringList getTargetPoolsList() { return targetPools_; } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @return The count of targetPools. */ public int getTargetPoolsCount() { return targetPools_.size(); } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param index The index of the element to return. * @return The targetPools at the given index. */ public java.lang.String getTargetPools(int index) { return targetPools_.get(index); } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param index The index of the value to return. * @return The bytes of the targetPools at the given index. */ public com.google.protobuf.ByteString getTargetPoolsBytes(int index) { return targetPools_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 234678500, fingerprint_); } for (int i = 0; i < targetPools_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 336072617, targetPools_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(234678500, fingerprint_); } { int dataSize = 0; for (int i = 0; i < targetPools_.size(); i++) { dataSize += computeStringSizeNoTag(targetPools_.getRaw(i)); } size += dataSize; size += 5 * getTargetPoolsList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest other = (com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest) obj; if (hasFingerprint() != other.hasFingerprint()) return false; if (hasFingerprint()) { if (!getFingerprint().equals(other.getFingerprint())) return false; } if (!getTargetPoolsList().equals(other.getTargetPoolsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasFingerprint()) { hash = (37 * hash) + FINGERPRINT_FIELD_NUMBER; hash = (53 * hash) + getFingerprint().hashCode(); } if (getTargetPoolsCount() > 0) { hash = (37 * hash) + TARGET_POOLS_FIELD_NUMBER; hash = (53 * hash) + getTargetPoolsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest) com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InstanceGroupManagersSetTargetPoolsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InstanceGroupManagersSetTargetPoolsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest.class, com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest.Builder.class); } // Construct using // com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; fingerprint_ = ""; targetPools_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InstanceGroupManagersSetTargetPoolsRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest build() { com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest buildPartial() { com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest result = new com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.fingerprint_ = fingerprint_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { targetPools_.makeImmutable(); result.targetPools_ = targetPools_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest) { return mergeFrom( (com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest other) { if (other == com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest .getDefaultInstance()) return this; if (other.hasFingerprint()) { fingerprint_ = other.fingerprint_; bitField0_ |= 0x00000001; onChanged(); } if (!other.targetPools_.isEmpty()) { if (targetPools_.isEmpty()) { targetPools_ = other.targetPools_; bitField0_ |= 0x00000002; } else { ensureTargetPoolsIsMutable(); targetPools_.addAll(other.targetPools_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 1877428002: { fingerprint_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 1877428002 case -1606386358: { java.lang.String s = input.readStringRequireUtf8(); ensureTargetPoolsIsMutable(); targetPools_.add(s); break; } // case -1606386358 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object fingerprint_ = ""; /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return Whether the fingerprint field is set. */ public boolean hasFingerprint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The fingerprint. */ public java.lang.String getFingerprint() { java.lang.Object ref = fingerprint_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); fingerprint_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return The bytes for fingerprint. */ public com.google.protobuf.ByteString getFingerprintBytes() { java.lang.Object ref = fingerprint_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); fingerprint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @param value The fingerprint to set. * @return This builder for chaining. */ public Builder setFingerprint(java.lang.String value) { if (value == null) { throw new NullPointerException(); } fingerprint_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @return This builder for chaining. */ public Builder clearFingerprint() { fingerprint_ = getDefaultInstance().getFingerprint(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. * </pre> * * <code>optional string fingerprint = 234678500;</code> * * @param value The bytes for fingerprint to set. * @return This builder for chaining. */ public Builder setFingerprintBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); fingerprint_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList targetPools_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureTargetPoolsIsMutable() { if (!targetPools_.isModifiable()) { targetPools_ = new com.google.protobuf.LazyStringArrayList(targetPools_); } bitField0_ |= 0x00000002; } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @return A list containing the targetPools. */ public com.google.protobuf.ProtocolStringList getTargetPoolsList() { targetPools_.makeImmutable(); return targetPools_; } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @return The count of targetPools. */ public int getTargetPoolsCount() { return targetPools_.size(); } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param index The index of the element to return. * @return The targetPools at the given index. */ public java.lang.String getTargetPools(int index) { return targetPools_.get(index); } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param index The index of the value to return. * @return The bytes of the targetPools at the given index. */ public com.google.protobuf.ByteString getTargetPoolsBytes(int index) { return targetPools_.getByteString(index); } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param index The index to set the value at. * @param value The targetPools to set. * @return This builder for chaining. */ public Builder setTargetPools(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTargetPoolsIsMutable(); targetPools_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param value The targetPools to add. * @return This builder for chaining. */ public Builder addTargetPools(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTargetPoolsIsMutable(); targetPools_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param values The targetPools to add. * @return This builder for chaining. */ public Builder addAllTargetPools(java.lang.Iterable<java.lang.String> values) { ensureTargetPoolsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, targetPools_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @return This builder for chaining. */ public Builder clearTargetPools() { targetPools_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * * * <pre> * The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. * </pre> * * <code>repeated string target_pools = 336072617;</code> * * @param value The bytes of the targetPools to add. * @return This builder for chaining. */ public Builder addTargetPoolsBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureTargetPoolsIsMutable(); targetPools_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest) private static final com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest(); } public static com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InstanceGroupManagersSetTargetPoolsRequest> PARSER = new com.google.protobuf.AbstractParser<InstanceGroupManagersSetTargetPoolsRequest>() { @java.lang.Override public InstanceGroupManagersSetTargetPoolsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException() .setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<InstanceGroupManagersSetTargetPoolsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InstanceGroupManagersSetTargetPoolsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.InstanceGroupManagersSetTargetPoolsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/kylin
36,550
src/common-server/src/test/java/org/apache/kylin/rest/controller/ResourceGroupControllerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.rest.controller; import static org.apache.kylin.common.constant.HttpConstant.HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON; import static org.apache.kylin.common.exception.code.ErrorCodeServer.PARAMETER_IN_PARAMETER_NOT_EMPTY; import static org.apache.kylin.common.exception.code.ErrorCodeServer.PROJECT_NOT_EXIST; import static org.apache.kylin.common.exception.code.ErrorCodeServer.REPEATED_INSTANCE; import static org.apache.kylin.common.exception.code.ErrorCodeServer.REQUEST_PARAMETER_EMPTY_OR_VALUE_EMPTY; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_BINDING_PROJECT_INVALID; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_DISABLE_FAILED; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_ENABLE_FAILED; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_ID_ALREADY_EXIST; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_ID_EMPTY; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_ID_NOT_EXIST_IN_MAPPING_INFO; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_ID_NOT_FOUND_IN_INSTANCE; import static org.apache.kylin.common.exception.code.ErrorCodeServer.RESOURCE_GROUP_INCOMPLETE_PARAMETER_LIST; import java.util.List; import java.util.Map; import org.apache.kylin.common.exception.KylinException; import org.apache.kylin.common.util.JsonUtil; import org.apache.kylin.common.util.NLocalFileMetadataTestCase; import org.apache.kylin.guava30.shaded.common.collect.Lists; import org.apache.kylin.guava30.shaded.common.collect.Maps; import org.apache.kylin.metadata.resourcegroup.KylinInstance; import org.apache.kylin.metadata.resourcegroup.ResourceGroup; import org.apache.kylin.metadata.resourcegroup.ResourceGroupEntity; import org.apache.kylin.metadata.resourcegroup.ResourceGroupManager; import org.apache.kylin.metadata.resourcegroup.ResourceGroupMappingInfo; import org.apache.kylin.rest.constant.Constant; import org.apache.kylin.rest.handler.resourcegroup.IResourceGroupRequestValidator; import org.apache.kylin.rest.handler.resourcegroup.ResourceGroupDisabledValidator; import org.apache.kylin.rest.handler.resourcegroup.ResourceGroupEnabledValidator; import org.apache.kylin.rest.handler.resourcegroup.ResourceGroupEntityValidator; import org.apache.kylin.rest.handler.resourcegroup.ResourceGroupFieldValidator; import org.apache.kylin.rest.handler.resourcegroup.ResourceGroupKylinInstanceValidator; import org.apache.kylin.rest.handler.resourcegroup.ResourceGroupMappingInfoValidator; import org.apache.kylin.rest.request.resourecegroup.ResourceGroupRequest; import org.apache.kylin.rest.service.ResourceGroupService; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.http.MediaType; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.google.gson.Gson; import lombok.val; public class ResourceGroupControllerTest extends NLocalFileMetadataTestCase { private MockMvc mockMvc; @Spy private List<IResourceGroupRequestValidator> requestFilterList = Lists.newArrayList(); @Mock private ResourceGroupService resourceGroupService; @InjectMocks private ResourceGroupController resourceGroupController = Mockito.spy(new ResourceGroupController()); private final Authentication authentication = new TestingAuthenticationToken("ADMIN", "ADMIN", Constant.ROLE_ADMIN); @Before public void setup() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(resourceGroupController) .defaultRequest(MockMvcRequestBuilders.get("/")).build(); SecurityContextHolder.getContext().setAuthentication(authentication); requestFilterList.add(new ResourceGroupFieldValidator()); requestFilterList.add(new ResourceGroupDisabledValidator()); requestFilterList.add(new ResourceGroupEnabledValidator()); requestFilterList.add(new ResourceGroupEntityValidator()); requestFilterList.add(new ResourceGroupKylinInstanceValidator()); requestFilterList.add(new ResourceGroupMappingInfoValidator()); overwriteSystemProp("HADOOP_USER_NAME", "root"); createTestMetadata(); } @After public void tearDown() { cleanupTestMetadata(); } //============= ResourceGroupFieldValidator =============== @Test public void testResourceGroupFieldFilterException1() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_INCOMPLETE_PARAMETER_LIST.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupFieldFilterException2() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setKylinInstances(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_INCOMPLETE_PARAMETER_LIST.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupFieldFilterException3() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setKylinInstances(Lists.newArrayList()); request.setResourceGroupEntities(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_INCOMPLETE_PARAMETER_LIST.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupFieldFilterException4() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setKylinInstances(Lists.newArrayList()); request.setResourceGroupMappingInfoList(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_INCOMPLETE_PARAMETER_LIST.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } //============= ResourceGroupDisabledValidator =============== @Test public void testResourceGroupDisabledFilter1() throws Exception { setResourceGroupEnabled(); Mockito.doReturn(Mockito.mock(ResourceGroup.class)).when(resourceGroupService).getResourceGroup(); ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(false); request.setResourceGroupMappingInfoList(Lists.newArrayList()); request.setResourceGroupEntities(Lists.newArrayList()); request.setKylinInstances(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); Mockito.verify(resourceGroupController).updateResourceGroup(request); } @Test public void testResourceGroupDisabledFilter2() throws Exception { Mockito.doReturn(Mockito.mock(ResourceGroup.class)).when(resourceGroupService).getResourceGroup(); ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(false); request.setResourceGroupMappingInfoList(Lists.newArrayList()); request.setResourceGroupEntities(Lists.newArrayList()); request.setKylinInstances(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); Mockito.verify(resourceGroupController).updateResourceGroup(request); } @Test public void testResourceGroupDisabledFilterException1() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(false); request.setResourceGroupMappingInfoList(Lists.newArrayList()); request.setKylinInstances(Lists.newArrayList()); request.setResourceGroupEntities(Lists.newArrayList()); Mockito.doReturn(Mockito.mock(ResourceGroup.class)).when(resourceGroupService).getResourceGroup(); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); Mockito.verify(resourceGroupController).updateResourceGroup(request); } @Test public void testResourceGroupDisabledFilterException2() throws Exception { setResourceGroupEnabled(); ResourceGroupRequest request = new ResourceGroupRequest(); List<KylinInstance> kylinInstances = Lists.newArrayList(new KylinInstance(), new KylinInstance()); request.setKylinInstances(kylinInstances); request.setResourceGroupMappingInfoList(Lists.newArrayList()); request.setResourceGroupEntities(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_DISABLE_FAILED.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } //============= ResourceGroupEnabledValidator =============== @Test public void testResourceGroupEnabledFilterException1() throws Exception { setResourceGroupEnabled(); Mockito.doReturn(Mockito.mock(ResourceGroup.class)).when(resourceGroupService).getResourceGroup(); ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); request.setKylinInstances(Lists.newArrayList()); request.setResourceGroupMappingInfoList(Lists.newArrayList()); request.setResourceGroupEntities(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_ENABLE_FAILED.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } //============= ResourceGroupEntityValidator =============== @Test public void testResourceGroupEntityFilterException1() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); request.setResourceGroupEntities(Lists.newArrayList(new ResourceGroupEntity(), new ResourceGroupEntity())); request.setKylinInstances(Lists.newArrayList()); request.setResourceGroupMappingInfoList(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_ID_EMPTY.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupEntityFilterException2() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); val entity2 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1, entity2)); request.setKylinInstances(Lists.newArrayList()); request.setResourceGroupMappingInfoList(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_ID_ALREADY_EXIST.getMsg("123"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } //============= ResourceGroupEntityValidator =============== @Test public void testResourceGroupKylinInstanceFilterException1() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); request.setKylinInstances(Lists.newArrayList(new KylinInstance())); request.setResourceGroupMappingInfoList(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(REQUEST_PARAMETER_EMPTY_OR_VALUE_EMPTY.getMsg("instance"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupKylinInstanceFilterException2() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); map.clear(); map.put("instance", "1.1.1.1:7070"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); request.setResourceGroupMappingInfoList(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(REQUEST_PARAMETER_EMPTY_OR_VALUE_EMPTY.getMsg("resource_group_id"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupKylinInstanceFilterException3() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "1"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); request.setResourceGroupMappingInfoList(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_ID_NOT_FOUND_IN_INSTANCE.getMsg("1"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupKylinInstanceFilterException4() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance, instance)); request.setResourceGroupMappingInfoList(Lists.newArrayList()); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(REPEATED_INSTANCE.getMsg(), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } //============= ResourceGroupMappingInfoValidator =============== @Test public void testResourceGroupMappingInfoFilterException1() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); request.setResourceGroupMappingInfoList(Lists.newArrayList(new ResourceGroupMappingInfo())); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(PARAMETER_IN_PARAMETER_NOT_EMPTY.getMsg("project", "mapping_info"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupMappingInfoFilterException2() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); map.clear(); map.put("project", "213"); val mapping = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupMappingInfo.class); request.setResourceGroupMappingInfoList(Lists.newArrayList(mapping)); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(PROJECT_NOT_EXIST.getMsg("213"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupMappingInfoFilterException3() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); map.clear(); map.put("project", "default"); val mapping = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupMappingInfo.class); request.setResourceGroupMappingInfoList(Lists.newArrayList(mapping)); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(PARAMETER_IN_PARAMETER_NOT_EMPTY.getMsg("resource_group_id", "mapping_info"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupMappingInfoFilterException4() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); map.clear(); map.put("project", "default"); map.put("resource_group_id", "1"); val mapping = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupMappingInfo.class); request.setResourceGroupMappingInfoList(Lists.newArrayList(mapping)); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_ID_NOT_EXIST_IN_MAPPING_INFO.getMsg("1"), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupMappingInfoFilterException5() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); Map<String, String> map2 = Maps.newHashMap(); map2.put("id", "124"); Map<String, String> map3 = Maps.newHashMap(); map3.put("id", "125"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); val entity2 = JsonUtil.readValue(new Gson().toJson(map2), ResourceGroupEntity.class); val entity3 = JsonUtil.readValue(new Gson().toJson(map3), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1, entity2, entity3)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); map.clear(); map.put("project", "default"); map.put("resource_group_id", "123"); map.put("request_type", "BUILD"); map2.clear(); map2.put("project", "default"); map2.put("resource_group_id", "124"); map2.put("request_type", "QUERY"); map3.clear(); map3.put("project", "default"); map3.put("resource_group_id", "125"); map3.put("request_type", "QUERY"); val mapping = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupMappingInfo.class); val mapping2 = JsonUtil.readValue(new Gson().toJson(map2), ResourceGroupMappingInfo.class); val mapping3 = JsonUtil.readValue(new Gson().toJson(map3), ResourceGroupMappingInfo.class); request.setResourceGroupMappingInfoList(Lists.newArrayList(mapping, mapping2, mapping3)); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_BINDING_PROJECT_INVALID.getMsg(map.get("project")), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } @Test public void testResourceGroupMappingInfoFilterException6() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); Map<String, String> map2 = Maps.newHashMap(); map2.put("id", "124"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); val entity2 = JsonUtil.readValue(new Gson().toJson(map2), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1, entity2)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); map.clear(); map.put("project", "default"); map.put("resource_group_id", "123"); map.put("request_type", "BUILD"); map2.clear(); map2.put("project", "default"); map2.put("resource_group_id", "124"); map2.put("request_type", "BUILD"); val mapping = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupMappingInfo.class); val mapping2 = JsonUtil.readValue(new Gson().toJson(map2), ResourceGroupMappingInfo.class); request.setResourceGroupMappingInfoList(Lists.newArrayList(mapping, mapping2)); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isInternalServerError()).andReturn(); Assert.assertThrows(RESOURCE_GROUP_BINDING_PROJECT_INVALID.getMsg(map.get("project")), KylinException.class, () -> resourceGroupController.updateResourceGroup(request)); } //============= pass case =============== @Test public void testPassCase() throws Exception { ResourceGroupRequest request = new ResourceGroupRequest(); request.setResourceGroupEnabled(true); Map<String, String> map = Maps.newHashMap(); map.put("id", "123"); Map<String, String> map2 = Maps.newHashMap(); map2.put("id", "124"); val entity1 = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupEntity.class); val entity2 = JsonUtil.readValue(new Gson().toJson(map2), ResourceGroupEntity.class); request.setResourceGroupEntities(Lists.newArrayList(entity1, entity2)); map.clear(); map.put("instance", "1.1.1.1:7070"); map.put("resource_group_id", "123"); val instance = JsonUtil.readValue(new Gson().toJson(map), KylinInstance.class); request.setKylinInstances(Lists.newArrayList(instance)); map.clear(); map.put("project", "default"); map.put("resource_group_id", "123"); map.put("request_type", "BUILD"); map2.clear(); map2.put("project", "default"); map2.put("resource_group_id", "124"); map2.put("request_type", "QUERY"); val mapping = JsonUtil.readValue(new Gson().toJson(map), ResourceGroupMappingInfo.class); val mapping2 = JsonUtil.readValue(new Gson().toJson(map2), ResourceGroupMappingInfo.class); request.setResourceGroupMappingInfoList(Lists.newArrayList(mapping, mapping2)); Mockito.doReturn(Mockito.mock(ResourceGroup.class)).when(resourceGroupService).getResourceGroup(); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); ResourceGroup resourceGroup = new ResourceGroup(); resourceGroup.setResourceGroupEnabled(true); resourceGroup.setResourceGroupEntities(Lists.newArrayList(entity1)); Mockito.doReturn(resourceGroup).when(resourceGroupService).getResourceGroup(); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); resourceGroup.setResourceGroupEnabled(true); resourceGroup.setResourceGroupEntities(Lists.newArrayList(entity1, entity2)); resourceGroup.setKylinInstances(Lists.newArrayList()); Mockito.doReturn(resourceGroup).when(resourceGroupService).getResourceGroup(); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); resourceGroup.setResourceGroupEnabled(true); resourceGroup.setResourceGroupEntities(Lists.newArrayList(entity1, entity2)); resourceGroup.setKylinInstances(Lists.newArrayList(instance)); resourceGroup.setResourceGroupMappingInfoList(Lists.newArrayList(mapping)); Mockito.doReturn(resourceGroup).when(resourceGroupService).getResourceGroup(); mockMvc.perform(MockMvcRequestBuilders.put("/api/resource_groups").contentType(MediaType.APPLICATION_JSON) .content(JsonUtil.writeValueAsString(request)) .accept(MediaType.parseMediaType(HTTP_VND_APACHE_KYLIN_V4_PUBLIC_JSON))) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); Mockito.verify(resourceGroupController, Mockito.times(4)).updateResourceGroup(request); } //============= methods =============== private void setResourceGroupEnabled() { val manager = ResourceGroupManager.getInstance(getTestConfig()); manager.getResourceGroup(); manager.updateResourceGroup(copyForWrite -> copyForWrite.setResourceGroupEnabled(true)); } }
googleapis/google-cloud-java
36,377
java-analytics-admin/proto-google-analytics-admin-v1beta/src/main/java/com/google/analytics/admin/v1beta/UpdatePropertyRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/analytics/admin/v1beta/analytics_admin.proto // Protobuf Java Version: 3.25.8 package com.google.analytics.admin.v1beta; /** * * * <pre> * Request message for UpdateProperty RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.UpdatePropertyRequest} */ public final class UpdatePropertyRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1beta.UpdatePropertyRequest) UpdatePropertyRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdatePropertyRequest.newBuilder() to construct. private UpdatePropertyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdatePropertyRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdatePropertyRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdatePropertyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdatePropertyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.UpdatePropertyRequest.class, com.google.analytics.admin.v1beta.UpdatePropertyRequest.Builder.class); } private int bitField0_; public static final int PROPERTY_FIELD_NUMBER = 1; private com.google.analytics.admin.v1beta.Property property_; /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the property field is set. */ @java.lang.Override public boolean hasProperty() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The property. */ @java.lang.Override public com.google.analytics.admin.v1beta.Property getProperty() { return property_ == null ? com.google.analytics.admin.v1beta.Property.getDefaultInstance() : property_; } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.analytics.admin.v1beta.PropertyOrBuilder getPropertyOrBuilder() { return property_ == null ? com.google.analytics.admin.v1beta.Property.getDefaultInstance() : property_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getProperty()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateMask()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getProperty()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.analytics.admin.v1beta.UpdatePropertyRequest)) { return super.equals(obj); } com.google.analytics.admin.v1beta.UpdatePropertyRequest other = (com.google.analytics.admin.v1beta.UpdatePropertyRequest) obj; if (hasProperty() != other.hasProperty()) return false; if (hasProperty()) { if (!getProperty().equals(other.getProperty())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasProperty()) { hash = (37 * hash) + PROPERTY_FIELD_NUMBER; hash = (53 * hash) + getProperty().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.analytics.admin.v1beta.UpdatePropertyRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for UpdateProperty RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.UpdatePropertyRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1beta.UpdatePropertyRequest) com.google.analytics.admin.v1beta.UpdatePropertyRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdatePropertyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdatePropertyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.UpdatePropertyRequest.class, com.google.analytics.admin.v1beta.UpdatePropertyRequest.Builder.class); } // Construct using com.google.analytics.admin.v1beta.UpdatePropertyRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getPropertyFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; property_ = null; if (propertyBuilder_ != null) { propertyBuilder_.dispose(); propertyBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdatePropertyRequest_descriptor; } @java.lang.Override public com.google.analytics.admin.v1beta.UpdatePropertyRequest getDefaultInstanceForType() { return com.google.analytics.admin.v1beta.UpdatePropertyRequest.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1beta.UpdatePropertyRequest build() { com.google.analytics.admin.v1beta.UpdatePropertyRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1beta.UpdatePropertyRequest buildPartial() { com.google.analytics.admin.v1beta.UpdatePropertyRequest result = new com.google.analytics.admin.v1beta.UpdatePropertyRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.analytics.admin.v1beta.UpdatePropertyRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.property_ = propertyBuilder_ == null ? property_ : propertyBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.analytics.admin.v1beta.UpdatePropertyRequest) { return mergeFrom((com.google.analytics.admin.v1beta.UpdatePropertyRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1beta.UpdatePropertyRequest other) { if (other == com.google.analytics.admin.v1beta.UpdatePropertyRequest.getDefaultInstance()) return this; if (other.hasProperty()) { mergeProperty(other.getProperty()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getPropertyFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.analytics.admin.v1beta.Property property_; private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.Property, com.google.analytics.admin.v1beta.Property.Builder, com.google.analytics.admin.v1beta.PropertyOrBuilder> propertyBuilder_; /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the property field is set. */ public boolean hasProperty() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The property. */ public com.google.analytics.admin.v1beta.Property getProperty() { if (propertyBuilder_ == null) { return property_ == null ? com.google.analytics.admin.v1beta.Property.getDefaultInstance() : property_; } else { return propertyBuilder_.getMessage(); } } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setProperty(com.google.analytics.admin.v1beta.Property value) { if (propertyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } property_ = value; } else { propertyBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setProperty(com.google.analytics.admin.v1beta.Property.Builder builderForValue) { if (propertyBuilder_ == null) { property_ = builderForValue.build(); } else { propertyBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeProperty(com.google.analytics.admin.v1beta.Property value) { if (propertyBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && property_ != null && property_ != com.google.analytics.admin.v1beta.Property.getDefaultInstance()) { getPropertyBuilder().mergeFrom(value); } else { property_ = value; } } else { propertyBuilder_.mergeFrom(value); } if (property_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearProperty() { bitField0_ = (bitField0_ & ~0x00000001); property_ = null; if (propertyBuilder_ != null) { propertyBuilder_.dispose(); propertyBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1beta.Property.Builder getPropertyBuilder() { bitField0_ |= 0x00000001; onChanged(); return getPropertyFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1beta.PropertyOrBuilder getPropertyOrBuilder() { if (propertyBuilder_ != null) { return propertyBuilder_.getMessageOrBuilder(); } else { return property_ == null ? com.google.analytics.admin.v1beta.Property.getDefaultInstance() : property_; } } /** * * * <pre> * Required. The property to update. * The property's `name` field is used to identify the property to be * updated. * </pre> * * <code> * .google.analytics.admin.v1beta.Property property = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.Property, com.google.analytics.admin.v1beta.Property.Builder, com.google.analytics.admin.v1beta.PropertyOrBuilder> getPropertyFieldBuilder() { if (propertyBuilder_ == null) { propertyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.Property, com.google.analytics.admin.v1beta.Property.Builder, com.google.analytics.admin.v1beta.PropertyOrBuilder>( getProperty(), getParentForChildren(), isClean()); property_ = null; } return propertyBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. The list of fields to be updated. Field names must be in snake * case (e.g., "field_to_update"). Omitted fields will not be updated. To * replace the entire entity, use one path with the string "*" to match all * fields. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.analytics.admin.v1beta.UpdatePropertyRequest) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1beta.UpdatePropertyRequest) private static final com.google.analytics.admin.v1beta.UpdatePropertyRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1beta.UpdatePropertyRequest(); } public static com.google.analytics.admin.v1beta.UpdatePropertyRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdatePropertyRequest> PARSER = new com.google.protobuf.AbstractParser<UpdatePropertyRequest>() { @java.lang.Override public UpdatePropertyRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<UpdatePropertyRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdatePropertyRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1beta.UpdatePropertyRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/rocketmq
36,696
store/src/main/java/org/apache/rocketmq/store/queue/ConsumeQueueStore.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.store.queue; import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.rocketmq.common.BoundaryType; import org.apache.rocketmq.common.ServiceThread; import org.apache.rocketmq.common.ThreadFactoryImpl; import org.apache.rocketmq.common.TopicConfig; import org.apache.rocketmq.common.attribute.CQType; import org.apache.rocketmq.common.message.MessageDecoder; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.topic.TopicValidator; import org.apache.rocketmq.common.utils.QueueTypeUtils; import org.apache.rocketmq.common.utils.ThreadUtils; import org.apache.rocketmq.store.CommitLog; import org.apache.rocketmq.store.ConsumeQueue; import org.apache.rocketmq.store.DefaultMessageStore; import org.apache.rocketmq.store.DispatchRequest; import org.apache.rocketmq.store.SelectMappedBufferResult; import org.apache.rocketmq.store.exception.StoreException; import static java.lang.String.format; import static org.apache.rocketmq.store.config.StorePathConfigHelper.getStorePathBatchConsumeQueue; import static org.apache.rocketmq.store.config.StorePathConfigHelper.getStorePathConsumeQueue; public class ConsumeQueueStore extends AbstractConsumeQueueStore { private final FlushConsumeQueueService flushConsumeQueueService; private final CorrectLogicOffsetService correctLogicOffsetService; private final CleanConsumeQueueService cleanConsumeQueueService; private long dispatchFromPhyOffset; private long dispatchFromStoreTimestamp; public ConsumeQueueStore(DefaultMessageStore messageStore) { super(messageStore); this.flushConsumeQueueService = new FlushConsumeQueueService(); this.correctLogicOffsetService = new CorrectLogicOffsetService(); this.cleanConsumeQueueService = new CleanConsumeQueueService(); } @Override public void start() { this.flushConsumeQueueService.start(); messageStore.getScheduledCleanQueueExecutorService().scheduleWithFixedDelay(this::cleanQueueFilesPeriodically, 1000 * 60, this.messageStoreConfig.getCleanResourceInterval(), TimeUnit.MILLISECONDS); log.info("Default ConsumeQueueStore start!"); } private void cleanQueueFilesPeriodically() { this.correctLogicOffsetService.run(); this.cleanConsumeQueueService.run(); } @Override public boolean load() { boolean cqLoadResult = loadConsumeQueues(getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), CQType.SimpleCQ); boolean bcqLoadResult = loadConsumeQueues(getStorePathBatchConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), CQType.BatchCQ); return cqLoadResult && bcqLoadResult; } @Override public void recover(boolean concurrently) { log.info("Start to recover consume queue concurrently={}", concurrently); if (concurrently) { recoverConcurrently(); } else { for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { this.recover(logic); } } } dispatchFromPhyOffset = this.getMaxPhyOffsetInConsumeQueue(); dispatchFromStoreTimestamp = this.messageStore.getStoreCheckpoint().getMinTimestamp(); } @Override public long getDispatchFromPhyOffset() { return getMaxPhyOffsetInConsumeQueue(); } public boolean recoverConcurrently() { int count = 0; for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { count += maps.values().size(); } final CountDownLatch countDownLatch = new CountDownLatch(count); BlockingQueue<Runnable> recoverQueue = new LinkedBlockingQueue<>(); final ExecutorService executor = buildExecutorService(recoverQueue, "RecoverConsumeQueueThread_"); List<FutureTask<Boolean>> result = new ArrayList<>(count); try { for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { for (final ConsumeQueueInterface logic : maps.values()) { FutureTask<Boolean> futureTask = new FutureTask<>(() -> { boolean ret = true; try { logic.recover(); } catch (Throwable e) { ret = false; log.error("Exception occurs while recover consume queue concurrently, " + "topic={}, queueId={}", logic.getTopic(), logic.getQueueId(), e); } finally { countDownLatch.countDown(); } return ret; }); result.add(futureTask); executor.submit(futureTask); } } countDownLatch.await(); for (FutureTask<Boolean> task : result) { if (task != null && task.isDone()) { if (!task.get()) { return false; } } } } catch (Exception e) { log.error("Exception occurs while recover consume queue concurrently", e); return false; } finally { executor.shutdown(); } return true; } @Override public boolean shutdown() { try { flush(); this.flushConsumeQueueService.shutdown(); } catch (StoreException e) { log.error("Failed to flush all consume queues", e); return false; } return true; } public void correctMinOffset(ConsumeQueueInterface consumeQueue, long minCommitLogOffset) { consumeQueue.correctMinOffset(minCommitLogOffset); } public void putMessagePositionInfoWrapper(DispatchRequest dispatchRequest) { ConsumeQueueInterface cq = this.findOrCreateConsumeQueue(dispatchRequest.getTopic(), dispatchRequest.getQueueId()); this.putMessagePositionInfoWrapper(cq, dispatchRequest); } @Override public long getOffsetInQueueByTime(String topic, int queueId, long timestamp, BoundaryType boundaryType) { ConsumeQueueInterface logic = findOrCreateConsumeQueue(topic, queueId); if (logic != null) { long resultOffset = logic.getOffsetInQueueByTime(timestamp, boundaryType); // Make sure the result offset is in valid range. resultOffset = Math.max(resultOffset, logic.getMinOffsetInQueue()); resultOffset = Math.min(resultOffset, logic.getMaxOffsetInQueue()); return resultOffset; } return 0; } private FileQueueLifeCycle getLifeCycle(String topic, int queueId) { return findOrCreateConsumeQueue(topic, queueId); } public boolean load(ConsumeQueueInterface consumeQueue) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); return fileQueueLifeCycle.load(); } private boolean loadConsumeQueues(String storePath, CQType cqType) { File dirLogic = new File(storePath); File[] fileTopicList = dirLogic.listFiles(); if (fileTopicList != null) { for (File fileTopic : fileTopicList) { String topic = fileTopic.getName(); File[] fileQueueIdList = fileTopic.listFiles(); if (fileQueueIdList != null) { for (File fileQueueId : fileQueueIdList) { int queueId; try { queueId = Integer.parseInt(fileQueueId.getName()); } catch (NumberFormatException e) { continue; } queueTypeShouldBe(topic, cqType); ConsumeQueueInterface logic = createConsumeQueueByType(cqType, topic, queueId, storePath); this.putConsumeQueue(topic, queueId, logic); if (!this.load(logic)) { return false; } } } } } log.info("load {} all over, OK", cqType); return true; } private ConsumeQueueInterface createConsumeQueueByType(CQType cqType, String topic, int queueId, String storePath) { if (Objects.equals(CQType.SimpleCQ, cqType)) { return new ConsumeQueue( topic, queueId, storePath, this.messageStoreConfig.getMappedFileSizeConsumeQueue(), this.messageStore, this); } else if (Objects.equals(CQType.BatchCQ, cqType)) { return new BatchConsumeQueue( topic, queueId, storePath, this.messageStoreConfig.getMapperFileSizeBatchConsumeQueue(), this.messageStore); } else { throw new RuntimeException(format("queue type %s is not supported.", cqType.toString())); } } private void queueTypeShouldBe(String topic, CQType cqTypeExpected) { Optional<TopicConfig> topicConfig = this.messageStore.getTopicConfig(topic); CQType cqTypeActual = QueueTypeUtils.getCQType(topicConfig); if (!Objects.equals(cqTypeExpected, cqTypeActual)) { throw new RuntimeException(format("The queue type of topic: %s should be %s, but is %s", topic, cqTypeExpected, cqTypeActual)); } } private ExecutorService buildExecutorService(BlockingQueue<Runnable> blockingQueue, String threadNamePrefix) { return ThreadUtils.newThreadPoolExecutor( this.messageStore.getBrokerConfig().getRecoverThreadPoolNums(), this.messageStore.getBrokerConfig().getRecoverThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, blockingQueue, new ThreadFactoryImpl(threadNamePrefix)); } public void recover(ConsumeQueueInterface consumeQueue) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); fileQueueLifeCycle.recover(); } @Override public long getMaxPhyOffsetInConsumeQueue() { long maxPhysicOffset = -1L; for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { if (logic.getMaxPhysicOffset() > maxPhysicOffset) { maxPhysicOffset = logic.getMaxPhysicOffset(); } } } return maxPhysicOffset; } @Override public long getMinOffsetInQueue(String topic, int queueId) { ConsumeQueueInterface logic = findOrCreateConsumeQueue(topic, queueId); if (logic != null) { return logic.getMinOffsetInQueue(); } return -1; } public void checkSelf(ConsumeQueueInterface consumeQueue) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); fileQueueLifeCycle.checkSelf(); } @Override public void checkSelf() { for (Map.Entry<String, ConcurrentMap<Integer, ConsumeQueueInterface>> topicEntry : this.consumeQueueTable.entrySet()) { for (Map.Entry<Integer, ConsumeQueueInterface> cqEntry : topicEntry.getValue().entrySet()) { this.checkSelf(cqEntry.getValue()); } } } public boolean flush(ConsumeQueueInterface consumeQueue, int flushLeastPages) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); return fileQueueLifeCycle.flush(flushLeastPages); } public void flush() throws StoreException { for (Map.Entry<String, ConcurrentMap<Integer, ConsumeQueueInterface>> topicEntry : this.consumeQueueTable.entrySet()) { for (Map.Entry<Integer, ConsumeQueueInterface> cqEntry : topicEntry.getValue().entrySet()) { flush(cqEntry.getValue(), 0); } } } @Override public void destroy(ConsumeQueueInterface consumeQueue) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); fileQueueLifeCycle.destroy(); } public int deleteExpiredFile(ConsumeQueueInterface consumeQueue, long minCommitLogPos) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); return fileQueueLifeCycle.deleteExpiredFile(minCommitLogPos); } public void truncateDirtyLogicFiles(ConsumeQueueInterface consumeQueue, long phyOffset) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); fileQueueLifeCycle.truncateDirtyLogicFiles(phyOffset); } public void swapMap(ConsumeQueueInterface consumeQueue, int reserveNum, long forceSwapIntervalMs, long normalSwapIntervalMs) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); fileQueueLifeCycle.swapMap(reserveNum, forceSwapIntervalMs, normalSwapIntervalMs); } public void cleanSwappedMap(ConsumeQueueInterface consumeQueue, long forceCleanSwapIntervalMs) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); fileQueueLifeCycle.cleanSwappedMap(forceCleanSwapIntervalMs); } public boolean isFirstFileAvailable(ConsumeQueueInterface consumeQueue) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); return fileQueueLifeCycle.isFirstFileAvailable(); } public boolean isFirstFileExist(ConsumeQueueInterface consumeQueue) { FileQueueLifeCycle fileQueueLifeCycle = getLifeCycle(consumeQueue.getTopic(), consumeQueue.getQueueId()); return fileQueueLifeCycle.isFirstFileExist(); } @Override public ConsumeQueueInterface findOrCreateConsumeQueue(String topic, int queueId) { ConcurrentMap<Integer, ConsumeQueueInterface> map = consumeQueueTable.get(topic); if (null == map) { ConcurrentMap<Integer, ConsumeQueueInterface> newMap = new ConcurrentHashMap<>(128); ConcurrentMap<Integer, ConsumeQueueInterface> oldMap = consumeQueueTable.putIfAbsent(topic, newMap); if (oldMap != null) { map = oldMap; } else { map = newMap; } } ConsumeQueueInterface logic = map.get(queueId); if (logic != null) { return logic; } ConsumeQueueInterface newLogic; Optional<TopicConfig> topicConfig = this.messageStore.getTopicConfig(topic); // TODO maybe the topic has been deleted. if (Objects.equals(CQType.BatchCQ, QueueTypeUtils.getCQType(topicConfig))) { newLogic = new BatchConsumeQueue( topic, queueId, getStorePathBatchConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), this.messageStoreConfig.getMapperFileSizeBatchConsumeQueue(), this.messageStore); } else { newLogic = new ConsumeQueue( topic, queueId, getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), this.messageStoreConfig.getMappedFileSizeConsumeQueue(), this.messageStore, this); } ConsumeQueueInterface oldLogic = map.putIfAbsent(queueId, newLogic); if (oldLogic != null) { logic = oldLogic; } else { logic = newLogic; } return logic; } @Override public ConsumeQueueInterface getConsumeQueue(String topic, int queueId) { ConcurrentMap<Integer, ConsumeQueueInterface> map = this.getConsumeQueueTable().get(topic); if (map == null) { return null; } return map.get(queueId); } public void setBatchTopicQueueTable(ConcurrentMap<String, Long> batchTopicQueueTable) { this.queueOffsetOperator.setBatchTopicQueueTable(batchTopicQueueTable); } public void updateQueueOffset(String topic, int queueId, long offset) { String topicQueueKey = topic + "-" + queueId; this.queueOffsetOperator.updateQueueOffset(topicQueueKey, offset); } private void putConsumeQueue(final String topic, final int queueId, final ConsumeQueueInterface consumeQueue) { ConcurrentMap<Integer/* queueId */, ConsumeQueueInterface> map = this.consumeQueueTable.get(topic); if (null == map) { map = new ConcurrentHashMap<>(); map.put(queueId, consumeQueue); this.consumeQueueTable.put(topic, map); } else { map.put(queueId, consumeQueue); } } @Override public void recoverOffsetTable(long minPhyOffset) { ConcurrentMap<String, Long> cqOffsetTable = new ConcurrentHashMap<>(1024); ConcurrentMap<String, Long> bcqOffsetTable = new ConcurrentHashMap<>(1024); for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { String key = logic.getTopic() + "-" + logic.getQueueId(); long maxOffsetInQueue = logic.getMaxOffsetInQueue(); if (Objects.equals(CQType.BatchCQ, logic.getCQType())) { bcqOffsetTable.put(key, maxOffsetInQueue); } else { cqOffsetTable.put(key, maxOffsetInQueue); } this.correctMinOffset(logic, minPhyOffset); } } // Correct unSubmit consumeOffset if (messageStoreConfig.isDuplicationEnable() || messageStore.getBrokerConfig().isEnableControllerMode()) { compensateForHA(cqOffsetTable); } this.setTopicQueueTable(cqOffsetTable); this.setBatchTopicQueueTable(bcqOffsetTable); } private void compensateForHA(ConcurrentMap<String, Long> cqOffsetTable) { SelectMappedBufferResult lastBuffer = null; long startReadOffset = messageStore.getCommitLog().getConfirmOffset() == -1 ? 0 : messageStore.getCommitLog().getConfirmOffset(); log.info("Correct unsubmitted offset...StartReadOffset = {}", startReadOffset); while ((lastBuffer = messageStore.selectOneMessageByOffset(startReadOffset)) != null) { try { if (lastBuffer.getStartOffset() > startReadOffset) { startReadOffset = lastBuffer.getStartOffset(); continue; } ByteBuffer bb = lastBuffer.getByteBuffer(); int magicCode = bb.getInt(bb.position() + 4); if (magicCode == CommitLog.BLANK_MAGIC_CODE) { startReadOffset += bb.getInt(bb.position()); continue; } else if (magicCode != MessageDecoder.MESSAGE_MAGIC_CODE) { throw new RuntimeException("Unknown magicCode: " + magicCode); } lastBuffer.getByteBuffer().mark(); DispatchRequest dispatchRequest = messageStore.getCommitLog().checkMessageAndReturnSize(lastBuffer.getByteBuffer(), true, messageStoreConfig.isDuplicationEnable(), true); if (!dispatchRequest.isSuccess()) break; lastBuffer.getByteBuffer().reset(); MessageExt msg = MessageDecoder.decode(lastBuffer.getByteBuffer(), true, false, false, false, true); if (msg == null) break; String key = msg.getTopic() + "-" + msg.getQueueId(); cqOffsetTable.put(key, msg.getQueueOffset() + 1); startReadOffset += msg.getStoreSize(); log.info("Correcting. Key:{}, start read Offset: {}", key, startReadOffset); } finally { if (lastBuffer != null) lastBuffer.release(); } } } /** * @param loadAfterDestroy file version cq do not need reload, so ignore */ @Override public void destroy(boolean loadAfterDestroy) { for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { this.destroy(logic); } } } @Override public void cleanExpired(long minCommitLogOffset) { Iterator<Entry<String, ConcurrentMap<Integer, ConsumeQueueInterface>>> it = this.consumeQueueTable.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, ConcurrentMap<Integer, ConsumeQueueInterface>> next = it.next(); String topic = next.getKey(); if (!TopicValidator.isSystemTopic(topic)) { ConcurrentMap<Integer, ConsumeQueueInterface> queueTable = next.getValue(); Iterator<Map.Entry<Integer, ConsumeQueueInterface>> itQT = queueTable.entrySet().iterator(); while (itQT.hasNext()) { Map.Entry<Integer, ConsumeQueueInterface> nextQT = itQT.next(); long maxCLOffsetInConsumeQueue = nextQT.getValue().getLastOffset(); if (maxCLOffsetInConsumeQueue == -1) { log.warn("maybe ConsumeQueue was created just now. topic={} queueId={} maxPhysicOffset={} minLogicOffset={}.", nextQT.getValue().getTopic(), nextQT.getValue().getQueueId(), nextQT.getValue().getMaxPhysicOffset(), nextQT.getValue().getMinLogicOffset()); } else if (maxCLOffsetInConsumeQueue < minCommitLogOffset) { log.info( "cleanExpiredConsumerQueue: {} {} consumer queue destroyed, minCommitLogOffset: {} maxCLOffsetInConsumeQueue: {}", topic, nextQT.getKey(), minCommitLogOffset, maxCLOffsetInConsumeQueue); removeTopicQueueTable(nextQT.getValue().getTopic(), nextQT.getValue().getQueueId()); this.destroy(nextQT.getValue()); itQT.remove(); } } if (queueTable.isEmpty()) { log.info("cleanExpiredConsumerQueue: {},topic destroyed", topic); it.remove(); } } } } @Override public void truncateDirty(long offsetToTruncate) { long maxPhyOffsetOfConsumeQueue = getMaxPhyOffsetInConsumeQueue(); if (maxPhyOffsetOfConsumeQueue >= offsetToTruncate) { log.warn("maxPhyOffsetOfConsumeQueue({}) >= processOffset({}), truncate dirty logic files", maxPhyOffsetOfConsumeQueue, offsetToTruncate); for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { this.truncateDirtyLogicFiles(logic, offsetToTruncate); } } } } @Override public long getTotalSize() { long totalSize = 0; for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : this.consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { totalSize += logic.getTotalSize(); } } return totalSize; } @Override public boolean isMappedFileMatchedRecover(long phyOffset, long storeTimestamp, boolean recoverNormally) { if (recoverNormally) { return phyOffset <= this.dispatchFromPhyOffset; } else { return storeTimestamp <= this.dispatchFromStoreTimestamp; } } public class FlushConsumeQueueService extends ServiceThread { private static final int RETRY_TIMES_OVER = 3; private long lastFlushTimestamp = 0; private void doFlush(int retryTimes) { int flushConsumeQueueLeastPages = messageStoreConfig.getFlushConsumeQueueLeastPages(); if (retryTimes == RETRY_TIMES_OVER) { flushConsumeQueueLeastPages = 0; } long logicsMsgTimestamp = 0; int flushConsumeQueueThoroughInterval = messageStoreConfig.getFlushConsumeQueueThoroughInterval(); long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis >= (this.lastFlushTimestamp + flushConsumeQueueThoroughInterval)) { this.lastFlushTimestamp = currentTimeMillis; flushConsumeQueueLeastPages = 0; logicsMsgTimestamp = messageStore.getStoreCheckpoint().getLogicsMsgTimestamp(); } for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : consumeQueueTable.values()) { for (ConsumeQueueInterface cq : maps.values()) { boolean result = false; for (int i = 0; i < retryTimes && !result; i++) { result = flush(cq, flushConsumeQueueLeastPages); } } } if (messageStoreConfig.isEnableCompaction()) { messageStore.getCompactionStore().flush(flushConsumeQueueLeastPages); } if (0 == flushConsumeQueueLeastPages) { if (logicsMsgTimestamp > 0) { messageStore.getStoreCheckpoint().setLogicsMsgTimestamp(logicsMsgTimestamp); } messageStore.getStoreCheckpoint().flush(); } } @Override public void run() { log.info(this.getServiceName() + " service started"); while (!this.isStopped()) { try { int interval = messageStoreConfig.getFlushIntervalConsumeQueue(); this.waitForRunning(interval); this.doFlush(1); } catch (Exception e) { log.warn(this.getServiceName() + " service has exception. ", e); } } this.doFlush(RETRY_TIMES_OVER); log.info(this.getServiceName() + " service end"); } @Override public String getServiceName() { if (messageStore.getBrokerConfig().isInBrokerContainer()) { return messageStore.getBrokerIdentity().getIdentifier() + FlushConsumeQueueService.class.getSimpleName(); } return FlushConsumeQueueService.class.getSimpleName(); } @Override public long getJoinTime() { return 1000 * 60; } } class CorrectLogicOffsetService { private long lastForceCorrectTime = -1L; public void run() { try { this.correctLogicMinOffset(); } catch (Throwable e) { log.warn(this.getServiceName() + " service has exception. ", e); } } private boolean needCorrect(ConsumeQueueInterface logic, long minPhyOffset, long lastForeCorrectTimeCurRun) { if (logic == null) { return false; } // If first exist and not available, it means first file may destroy failed, delete it. if (isFirstFileExist(logic) && !isFirstFileAvailable(logic)) { log.error("CorrectLogicOffsetService.needCorrect. first file not available, trigger correct." + " topic:{}, queue:{}, maxPhyOffset in queue:{}, minPhyOffset " + "in commit log:{}, minOffset in queue:{}, maxOffset in queue:{}, cqType:{}" , logic.getTopic(), logic.getQueueId(), logic.getMaxPhysicOffset() , minPhyOffset, logic.getMinOffsetInQueue(), logic.getMaxOffsetInQueue(), logic.getCQType()); return true; } // logic.getMaxPhysicOffset() or minPhyOffset = -1 // means there is no message in current queue, so no need to correct. if (logic.getMaxPhysicOffset() == -1 || minPhyOffset == -1) { return false; } if (logic.getMaxPhysicOffset() < minPhyOffset) { if (logic.getMinOffsetInQueue() < logic.getMaxOffsetInQueue()) { log.error("CorrectLogicOffsetService.needCorrect. logic max phy offset: {} is less than min phy offset: {}, " + "but min offset: {} is less than max offset: {}. topic:{}, queue:{}, cqType:{}." , logic.getMaxPhysicOffset(), minPhyOffset, logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return true; } else if (logic.getMinOffsetInQueue() == logic.getMaxOffsetInQueue()) { return false; } else { log.error("CorrectLogicOffsetService.needCorrect. It should not happen, logic max phy offset: {} is less than min phy offset: {}," + " but min offset: {} is larger than max offset: {}. topic:{}, queue:{}, cqType:{}" , logic.getMaxPhysicOffset(), minPhyOffset, logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return false; } } //the logic.getMaxPhysicOffset() >= minPhyOffset int forceCorrectInterval = messageStoreConfig.getCorrectLogicMinOffsetForceInterval(); if ((System.currentTimeMillis() - lastForeCorrectTimeCurRun) > forceCorrectInterval) { lastForceCorrectTime = System.currentTimeMillis(); CqUnit cqUnit = logic.getEarliestUnit(); if (cqUnit == null) { if (logic.getMinOffsetInQueue() == logic.getMaxOffsetInQueue()) { return false; } else { log.error("CorrectLogicOffsetService.needCorrect. cqUnit is null, logic max phy offset: {} is greater than min phy offset: {}, " + "but min offset: {} is not equal to max offset: {}. topic:{}, queue:{}, cqType:{}." , logic.getMaxPhysicOffset(), minPhyOffset, logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return true; } } if (cqUnit.getPos() < minPhyOffset) { log.error("CorrectLogicOffsetService.needCorrect. logic max phy offset: {} is greater than min phy offset: {}, " + "but minPhyPos in cq is: {}. min offset in queue: {}, max offset in queue: {}, topic:{}, queue:{}, cqType:{}." , logic.getMaxPhysicOffset(), minPhyOffset, cqUnit.getPos(), logic.getMinOffsetInQueue() , logic.getMaxOffsetInQueue(), logic.getTopic(), logic.getQueueId(), logic.getCQType()); return true; } if (cqUnit.getPos() >= minPhyOffset) { // Normal case, do not need to correct. return false; } } return false; } private void correctLogicMinOffset() { long lastForeCorrectTimeCurRun = lastForceCorrectTime; long minPhyOffset = messageStore.getMinPhyOffset(); for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { if (Objects.equals(CQType.SimpleCQ, logic.getCQType())) { // cq is not supported for now. continue; } if (needCorrect(logic, minPhyOffset, lastForeCorrectTimeCurRun)) { doCorrect(logic, minPhyOffset); } } } } private void doCorrect(ConsumeQueueInterface logic, long minPhyOffset) { deleteExpiredFile(logic, minPhyOffset); int sleepIntervalWhenCorrectMinOffset = messageStoreConfig.getCorrectLogicMinOffsetSleepInterval(); if (sleepIntervalWhenCorrectMinOffset > 0) { try { Thread.sleep(sleepIntervalWhenCorrectMinOffset); } catch (InterruptedException ignored) { } } } public String getServiceName() { if (messageStore.getBrokerConfig().isInBrokerContainer()) { return messageStore.getBrokerConfig().getIdentifier() + CorrectLogicOffsetService.class.getSimpleName(); } return CorrectLogicOffsetService.class.getSimpleName(); } } public class CleanConsumeQueueService { protected long lastPhysicalMinOffset = 0; public void run() { try { this.deleteExpiredFiles(); } catch (Throwable e) { log.warn(this.getServiceName() + " service has exception. ", e); } } protected void deleteExpiredFiles() { int deleteLogicsFilesInterval = messageStoreConfig.getDeleteConsumeQueueFilesInterval(); long minOffset = messageStore.getCommitLog().getMinOffset(); if (minOffset > this.lastPhysicalMinOffset) { this.lastPhysicalMinOffset = minOffset; for (ConcurrentMap<Integer, ConsumeQueueInterface> maps : consumeQueueTable.values()) { for (ConsumeQueueInterface logic : maps.values()) { int deleteCount = deleteExpiredFile(logic, minOffset); if (deleteCount > 0 && deleteLogicsFilesInterval > 0) { try { Thread.sleep(deleteLogicsFilesInterval); } catch (InterruptedException ignored) { } } } } messageStore.getIndexService().deleteExpiredFile(minOffset); } } public String getServiceName() { return messageStore.getBrokerConfig().getIdentifier() + CleanConsumeQueueService.class.getSimpleName(); } } }
googleapis/google-cloud-java
36,385
java-container/proto-google-cloud-container-v1beta1/src/main/java/com/google/container/v1beta1/ListClustersRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1beta1/cluster_service.proto // Protobuf Java Version: 3.25.8 package com.google.container.v1beta1; /** * * * <pre> * ListClustersRequest lists clusters. * </pre> * * Protobuf type {@code google.container.v1beta1.ListClustersRequest} */ public final class ListClustersRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1beta1.ListClustersRequest) ListClustersRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListClustersRequest.newBuilder() to construct. private ListClustersRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListClustersRequest() { projectId_ = ""; zone_ = ""; parent_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListClustersRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListClustersRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListClustersRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.ListClustersRequest.class, com.google.container.v1beta1.ListClustersRequest.Builder.class); } public static final int PROJECT_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object projectId_ = ""; /** * * * <pre> * Deprecated. The Google Developers Console [project ID or project * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). * This field has been deprecated and replaced by the parent field. * </pre> * * <code>string project_id = 1 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.project_id is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4477 * @return The projectId. */ @java.lang.Override @java.lang.Deprecated public java.lang.String getProjectId() { java.lang.Object ref = projectId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); projectId_ = s; return s; } } /** * * * <pre> * Deprecated. The Google Developers Console [project ID or project * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). * This field has been deprecated and replaced by the parent field. * </pre> * * <code>string project_id = 1 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.project_id is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4477 * @return The bytes for projectId. */ @java.lang.Override @java.lang.Deprecated public com.google.protobuf.ByteString getProjectIdBytes() { java.lang.Object ref = projectId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); projectId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ZONE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object zone_ = ""; /** * * * <pre> * Deprecated. The name of the Google Compute Engine * [zone](https://cloud.google.com/compute/docs/zones#available) * in which the cluster resides, or "-" for all zones. This field has been * deprecated and replaced by the parent field. * </pre> * * <code>string zone = 2 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.zone is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4483 * @return The zone. */ @java.lang.Override @java.lang.Deprecated public java.lang.String getZone() { java.lang.Object ref = zone_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); zone_ = s; return s; } } /** * * * <pre> * Deprecated. The name of the Google Compute Engine * [zone](https://cloud.google.com/compute/docs/zones#available) * in which the cluster resides, or "-" for all zones. This field has been * deprecated and replaced by the parent field. * </pre> * * <code>string zone = 2 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.zone is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4483 * @return The bytes for zone. */ @java.lang.Override @java.lang.Deprecated public com.google.protobuf.ByteString getZoneBytes() { java.lang.Object ref = zone_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); zone_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PARENT_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * The parent (project and location) where the clusters will be listed. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * Location "-" matches all zones and all regions. * </pre> * * <code>string parent = 4;</code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * The parent (project and location) where the clusters will be listed. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * Location "-" matches all zones and all regions. * </pre> * * <code>string parent = 4;</code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(projectId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, projectId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(zone_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, zone_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, parent_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(projectId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, projectId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(zone_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, zone_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, parent_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.container.v1beta1.ListClustersRequest)) { return super.equals(obj); } com.google.container.v1beta1.ListClustersRequest other = (com.google.container.v1beta1.ListClustersRequest) obj; if (!getProjectId().equals(other.getProjectId())) return false; if (!getZone().equals(other.getZone())) return false; if (!getParent().equals(other.getParent())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PROJECT_ID_FIELD_NUMBER; hash = (53 * hash) + getProjectId().hashCode(); hash = (37 * hash) + ZONE_FIELD_NUMBER; hash = (53 * hash) + getZone().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1beta1.ListClustersRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.ListClustersRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.ListClustersRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1beta1.ListClustersRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.ListClustersRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.container.v1beta1.ListClustersRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * ListClustersRequest lists clusters. * </pre> * * Protobuf type {@code google.container.v1beta1.ListClustersRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1beta1.ListClustersRequest) com.google.container.v1beta1.ListClustersRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListClustersRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListClustersRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.ListClustersRequest.class, com.google.container.v1beta1.ListClustersRequest.Builder.class); } // Construct using com.google.container.v1beta1.ListClustersRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; projectId_ = ""; zone_ = ""; parent_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_ListClustersRequest_descriptor; } @java.lang.Override public com.google.container.v1beta1.ListClustersRequest getDefaultInstanceForType() { return com.google.container.v1beta1.ListClustersRequest.getDefaultInstance(); } @java.lang.Override public com.google.container.v1beta1.ListClustersRequest build() { com.google.container.v1beta1.ListClustersRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1beta1.ListClustersRequest buildPartial() { com.google.container.v1beta1.ListClustersRequest result = new com.google.container.v1beta1.ListClustersRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.container.v1beta1.ListClustersRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.projectId_ = projectId_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.zone_ = zone_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.parent_ = parent_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.container.v1beta1.ListClustersRequest) { return mergeFrom((com.google.container.v1beta1.ListClustersRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1beta1.ListClustersRequest other) { if (other == com.google.container.v1beta1.ListClustersRequest.getDefaultInstance()) return this; if (!other.getProjectId().isEmpty()) { projectId_ = other.projectId_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getZone().isEmpty()) { zone_ = other.zone_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { projectId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { zone_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 34: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object projectId_ = ""; /** * * * <pre> * Deprecated. The Google Developers Console [project ID or project * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). * This field has been deprecated and replaced by the parent field. * </pre> * * <code>string project_id = 1 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.project_id is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4477 * @return The projectId. */ @java.lang.Deprecated public java.lang.String getProjectId() { java.lang.Object ref = projectId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); projectId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Deprecated. The Google Developers Console [project ID or project * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). * This field has been deprecated and replaced by the parent field. * </pre> * * <code>string project_id = 1 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.project_id is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4477 * @return The bytes for projectId. */ @java.lang.Deprecated public com.google.protobuf.ByteString getProjectIdBytes() { java.lang.Object ref = projectId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); projectId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Deprecated. The Google Developers Console [project ID or project * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). * This field has been deprecated and replaced by the parent field. * </pre> * * <code>string project_id = 1 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.project_id is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4477 * @param value The projectId to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setProjectId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } projectId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Deprecated. The Google Developers Console [project ID or project * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). * This field has been deprecated and replaced by the parent field. * </pre> * * <code>string project_id = 1 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.project_id is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4477 * @return This builder for chaining. */ @java.lang.Deprecated public Builder clearProjectId() { projectId_ = getDefaultInstance().getProjectId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Deprecated. The Google Developers Console [project ID or project * number](https://cloud.google.com/resource-manager/docs/creating-managing-projects). * This field has been deprecated and replaced by the parent field. * </pre> * * <code>string project_id = 1 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.project_id is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4477 * @param value The bytes for projectId to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setProjectIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); projectId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object zone_ = ""; /** * * * <pre> * Deprecated. The name of the Google Compute Engine * [zone](https://cloud.google.com/compute/docs/zones#available) * in which the cluster resides, or "-" for all zones. This field has been * deprecated and replaced by the parent field. * </pre> * * <code>string zone = 2 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.zone is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4483 * @return The zone. */ @java.lang.Deprecated public java.lang.String getZone() { java.lang.Object ref = zone_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); zone_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Deprecated. The name of the Google Compute Engine * [zone](https://cloud.google.com/compute/docs/zones#available) * in which the cluster resides, or "-" for all zones. This field has been * deprecated and replaced by the parent field. * </pre> * * <code>string zone = 2 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.zone is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4483 * @return The bytes for zone. */ @java.lang.Deprecated public com.google.protobuf.ByteString getZoneBytes() { java.lang.Object ref = zone_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); zone_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Deprecated. The name of the Google Compute Engine * [zone](https://cloud.google.com/compute/docs/zones#available) * in which the cluster resides, or "-" for all zones. This field has been * deprecated and replaced by the parent field. * </pre> * * <code>string zone = 2 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.zone is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4483 * @param value The zone to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setZone(java.lang.String value) { if (value == null) { throw new NullPointerException(); } zone_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Deprecated. The name of the Google Compute Engine * [zone](https://cloud.google.com/compute/docs/zones#available) * in which the cluster resides, or "-" for all zones. This field has been * deprecated and replaced by the parent field. * </pre> * * <code>string zone = 2 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.zone is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4483 * @return This builder for chaining. */ @java.lang.Deprecated public Builder clearZone() { zone_ = getDefaultInstance().getZone(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Deprecated. The name of the Google Compute Engine * [zone](https://cloud.google.com/compute/docs/zones#available) * in which the cluster resides, or "-" for all zones. This field has been * deprecated and replaced by the parent field. * </pre> * * <code>string zone = 2 [deprecated = true];</code> * * @deprecated google.container.v1beta1.ListClustersRequest.zone is deprecated. See * google/container/v1beta1/cluster_service.proto;l=4483 * @param value The bytes for zone to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setZoneBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); zone_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object parent_ = ""; /** * * * <pre> * The parent (project and location) where the clusters will be listed. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * Location "-" matches all zones and all regions. * </pre> * * <code>string parent = 4;</code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The parent (project and location) where the clusters will be listed. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * Location "-" matches all zones and all regions. * </pre> * * <code>string parent = 4;</code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The parent (project and location) where the clusters will be listed. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * Location "-" matches all zones and all regions. * </pre> * * <code>string parent = 4;</code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The parent (project and location) where the clusters will be listed. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * Location "-" matches all zones and all regions. * </pre> * * <code>string parent = 4;</code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * The parent (project and location) where the clusters will be listed. * Specified in the format `projects/&#42;&#47;locations/&#42;`. * Location "-" matches all zones and all regions. * </pre> * * <code>string parent = 4;</code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.container.v1beta1.ListClustersRequest) } // @@protoc_insertion_point(class_scope:google.container.v1beta1.ListClustersRequest) private static final com.google.container.v1beta1.ListClustersRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1beta1.ListClustersRequest(); } public static com.google.container.v1beta1.ListClustersRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListClustersRequest> PARSER = new com.google.protobuf.AbstractParser<ListClustersRequest>() { @java.lang.Override public ListClustersRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListClustersRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListClustersRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1beta1.ListClustersRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,653
java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/PublicAdvertisedPrefixesStubSettings.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.compute.v1.stub; import static com.google.cloud.compute.v1.PublicAdvertisedPrefixesClient.ListPagedResponse; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.httpjson.GaxHttpJsonProperties; import com.google.api.gax.httpjson.HttpJsonTransportChannel; import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider; import com.google.api.gax.httpjson.ProtoOperationTransformers; import com.google.api.gax.longrunning.OperationSnapshot; import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.PagedListDescriptor; import com.google.api.gax.rpc.PagedListResponseFactory; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.compute.v1.AnnouncePublicAdvertisedPrefixeRequest; import com.google.cloud.compute.v1.DeletePublicAdvertisedPrefixeRequest; import com.google.cloud.compute.v1.GetPublicAdvertisedPrefixeRequest; import com.google.cloud.compute.v1.InsertPublicAdvertisedPrefixeRequest; import com.google.cloud.compute.v1.ListPublicAdvertisedPrefixesRequest; import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.PatchPublicAdvertisedPrefixeRequest; import com.google.cloud.compute.v1.PublicAdvertisedPrefix; import com.google.cloud.compute.v1.PublicAdvertisedPrefixList; import com.google.cloud.compute.v1.WithdrawPublicAdvertisedPrefixeRequest; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import java.io.IOException; import java.time.Duration; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link PublicAdvertisedPrefixesStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (compute.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the * [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings) * of get: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * PublicAdvertisedPrefixesStubSettings.Builder publicAdvertisedPrefixesSettingsBuilder = * PublicAdvertisedPrefixesStubSettings.newBuilder(); * publicAdvertisedPrefixesSettingsBuilder * .getSettings() * .setRetrySettings( * publicAdvertisedPrefixesSettingsBuilder * .getSettings() * .getRetrySettings() * .toBuilder() * .setInitialRetryDelayDuration(Duration.ofSeconds(1)) * .setInitialRpcTimeoutDuration(Duration.ofSeconds(5)) * .setMaxAttempts(5) * .setMaxRetryDelayDuration(Duration.ofSeconds(30)) * .setMaxRpcTimeoutDuration(Duration.ofSeconds(60)) * .setRetryDelayMultiplier(1.3) * .setRpcTimeoutMultiplier(1.5) * .setTotalTimeoutDuration(Duration.ofSeconds(300)) * .build()); * PublicAdvertisedPrefixesStubSettings publicAdvertisedPrefixesSettings = * publicAdvertisedPrefixesSettingsBuilder.build(); * }</pre> * * Please refer to the [Client Side Retry * Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for * additional support in setting retries. * * <p>To configure the RetrySettings of a Long Running Operation method, create an * OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to * configure the RetrySettings for announce: * * <pre>{@code * // This snippet has been automatically generated and should be regarded as a code template only. * // It will require modifications to work: * // - It may require correct/in-range values for request initialization. * // - It may require specifying regional endpoints when creating the service client as shown in * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library * PublicAdvertisedPrefixesStubSettings.Builder publicAdvertisedPrefixesSettingsBuilder = * PublicAdvertisedPrefixesStubSettings.newBuilder(); * TimedRetryAlgorithm timedRetryAlgorithm = * OperationalTimedPollAlgorithm.create( * RetrySettings.newBuilder() * .setInitialRetryDelayDuration(Duration.ofMillis(500)) * .setRetryDelayMultiplier(1.5) * .setMaxRetryDelayDuration(Duration.ofMillis(5000)) * .setTotalTimeoutDuration(Duration.ofHours(24)) * .build()); * publicAdvertisedPrefixesSettingsBuilder * .createClusterOperationSettings() * .setPollingAlgorithm(timedRetryAlgorithm) * .build(); * }</pre> */ @Generated("by gapic-generator-java") public class PublicAdvertisedPrefixesStubSettings extends StubSettings<PublicAdvertisedPrefixesStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder() .add("https://www.googleapis.com/auth/compute") .add("https://www.googleapis.com/auth/cloud-platform") .build(); private final UnaryCallSettings<AnnouncePublicAdvertisedPrefixeRequest, Operation> announceSettings; private final OperationCallSettings<AnnouncePublicAdvertisedPrefixeRequest, Operation, Operation> announceOperationSettings; private final UnaryCallSettings<DeletePublicAdvertisedPrefixeRequest, Operation> deleteSettings; private final OperationCallSettings<DeletePublicAdvertisedPrefixeRequest, Operation, Operation> deleteOperationSettings; private final UnaryCallSettings<GetPublicAdvertisedPrefixeRequest, PublicAdvertisedPrefix> getSettings; private final UnaryCallSettings<InsertPublicAdvertisedPrefixeRequest, Operation> insertSettings; private final OperationCallSettings<InsertPublicAdvertisedPrefixeRequest, Operation, Operation> insertOperationSettings; private final PagedCallSettings< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, ListPagedResponse> listSettings; private final UnaryCallSettings<PatchPublicAdvertisedPrefixeRequest, Operation> patchSettings; private final OperationCallSettings<PatchPublicAdvertisedPrefixeRequest, Operation, Operation> patchOperationSettings; private final UnaryCallSettings<WithdrawPublicAdvertisedPrefixeRequest, Operation> withdrawSettings; private final OperationCallSettings<WithdrawPublicAdvertisedPrefixeRequest, Operation, Operation> withdrawOperationSettings; private static final PagedListDescriptor< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, PublicAdvertisedPrefix> LIST_PAGE_STR_DESC = new PagedListDescriptor< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, PublicAdvertisedPrefix>() { @Override public String emptyToken() { return ""; } @Override public ListPublicAdvertisedPrefixesRequest injectToken( ListPublicAdvertisedPrefixesRequest payload, String token) { return ListPublicAdvertisedPrefixesRequest.newBuilder(payload) .setPageToken(token) .build(); } @Override public ListPublicAdvertisedPrefixesRequest injectPageSize( ListPublicAdvertisedPrefixesRequest payload, int pageSize) { return ListPublicAdvertisedPrefixesRequest.newBuilder(payload) .setMaxResults(pageSize) .build(); } @Override public Integer extractPageSize(ListPublicAdvertisedPrefixesRequest payload) { return payload.getMaxResults(); } @Override public String extractNextToken(PublicAdvertisedPrefixList payload) { return payload.getNextPageToken(); } @Override public Iterable<PublicAdvertisedPrefix> extractResources( PublicAdvertisedPrefixList payload) { return payload.getItemsList(); } }; private static final PagedListResponseFactory< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, ListPagedResponse> LIST_PAGE_STR_FACT = new PagedListResponseFactory< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, ListPagedResponse>() { @Override public ApiFuture<ListPagedResponse> getFuturePagedResponse( UnaryCallable<ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList> callable, ListPublicAdvertisedPrefixesRequest request, ApiCallContext context, ApiFuture<PublicAdvertisedPrefixList> futureResponse) { PageContext< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, PublicAdvertisedPrefix> pageContext = PageContext.create(callable, LIST_PAGE_STR_DESC, request, context); return ListPagedResponse.createAsync(pageContext, futureResponse); } }; /** Returns the object with the settings used for calls to announce. */ public UnaryCallSettings<AnnouncePublicAdvertisedPrefixeRequest, Operation> announceSettings() { return announceSettings; } /** Returns the object with the settings used for calls to announce. */ public OperationCallSettings<AnnouncePublicAdvertisedPrefixeRequest, Operation, Operation> announceOperationSettings() { return announceOperationSettings; } /** Returns the object with the settings used for calls to delete. */ public UnaryCallSettings<DeletePublicAdvertisedPrefixeRequest, Operation> deleteSettings() { return deleteSettings; } /** Returns the object with the settings used for calls to delete. */ public OperationCallSettings<DeletePublicAdvertisedPrefixeRequest, Operation, Operation> deleteOperationSettings() { return deleteOperationSettings; } /** Returns the object with the settings used for calls to get. */ public UnaryCallSettings<GetPublicAdvertisedPrefixeRequest, PublicAdvertisedPrefix> getSettings() { return getSettings; } /** Returns the object with the settings used for calls to insert. */ public UnaryCallSettings<InsertPublicAdvertisedPrefixeRequest, Operation> insertSettings() { return insertSettings; } /** Returns the object with the settings used for calls to insert. */ public OperationCallSettings<InsertPublicAdvertisedPrefixeRequest, Operation, Operation> insertOperationSettings() { return insertOperationSettings; } /** Returns the object with the settings used for calls to list. */ public PagedCallSettings< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, ListPagedResponse> listSettings() { return listSettings; } /** Returns the object with the settings used for calls to patch. */ public UnaryCallSettings<PatchPublicAdvertisedPrefixeRequest, Operation> patchSettings() { return patchSettings; } /** Returns the object with the settings used for calls to patch. */ public OperationCallSettings<PatchPublicAdvertisedPrefixeRequest, Operation, Operation> patchOperationSettings() { return patchOperationSettings; } /** Returns the object with the settings used for calls to withdraw. */ public UnaryCallSettings<WithdrawPublicAdvertisedPrefixeRequest, Operation> withdrawSettings() { return withdrawSettings; } /** Returns the object with the settings used for calls to withdraw. */ public OperationCallSettings<WithdrawPublicAdvertisedPrefixeRequest, Operation, Operation> withdrawOperationSettings() { return withdrawOperationSettings; } public PublicAdvertisedPrefixesStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { return HttpJsonPublicAdvertisedPrefixesStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns the default service name. */ @Override public String getServiceName() { return "compute"; } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ @ObsoleteApi("Use getEndpoint() instead") public static String getDefaultEndpoint() { return "compute.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "compute.mtls.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder() .setScopesToApply(DEFAULT_SERVICE_SCOPES) .setUseJwtAccessWithScope(true); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingHttpJsonChannelProvider.Builder defaultHttpJsonTransportProviderBuilder() { return InstantiatingHttpJsonChannelProvider.newBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultHttpJsonTransportProviderBuilder().build(); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(PublicAdvertisedPrefixesStubSettings.class)) .setTransportToken( GaxHttpJsonProperties.getHttpJsonTokenName(), GaxHttpJsonProperties.getHttpJsonVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected PublicAdvertisedPrefixesStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); announceSettings = settingsBuilder.announceSettings().build(); announceOperationSettings = settingsBuilder.announceOperationSettings().build(); deleteSettings = settingsBuilder.deleteSettings().build(); deleteOperationSettings = settingsBuilder.deleteOperationSettings().build(); getSettings = settingsBuilder.getSettings().build(); insertSettings = settingsBuilder.insertSettings().build(); insertOperationSettings = settingsBuilder.insertOperationSettings().build(); listSettings = settingsBuilder.listSettings().build(); patchSettings = settingsBuilder.patchSettings().build(); patchOperationSettings = settingsBuilder.patchOperationSettings().build(); withdrawSettings = settingsBuilder.withdrawSettings().build(); withdrawOperationSettings = settingsBuilder.withdrawOperationSettings().build(); } /** Builder for PublicAdvertisedPrefixesStubSettings. */ public static class Builder extends StubSettings.Builder<PublicAdvertisedPrefixesStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder<AnnouncePublicAdvertisedPrefixeRequest, Operation> announceSettings; private final OperationCallSettings.Builder< AnnouncePublicAdvertisedPrefixeRequest, Operation, Operation> announceOperationSettings; private final UnaryCallSettings.Builder<DeletePublicAdvertisedPrefixeRequest, Operation> deleteSettings; private final OperationCallSettings.Builder< DeletePublicAdvertisedPrefixeRequest, Operation, Operation> deleteOperationSettings; private final UnaryCallSettings.Builder< GetPublicAdvertisedPrefixeRequest, PublicAdvertisedPrefix> getSettings; private final UnaryCallSettings.Builder<InsertPublicAdvertisedPrefixeRequest, Operation> insertSettings; private final OperationCallSettings.Builder< InsertPublicAdvertisedPrefixeRequest, Operation, Operation> insertOperationSettings; private final PagedCallSettings.Builder< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, ListPagedResponse> listSettings; private final UnaryCallSettings.Builder<PatchPublicAdvertisedPrefixeRequest, Operation> patchSettings; private final OperationCallSettings.Builder< PatchPublicAdvertisedPrefixeRequest, Operation, Operation> patchOperationSettings; private final UnaryCallSettings.Builder<WithdrawPublicAdvertisedPrefixeRequest, Operation> withdrawSettings; private final OperationCallSettings.Builder< WithdrawPublicAdvertisedPrefixeRequest, Operation, Operation> withdrawOperationSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList())); definitions.put( "retry_policy_0_codes", ImmutableSet.copyOf( Lists.<StatusCode.Code>newArrayList( StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE))); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRpcTimeoutDuration(Duration.ofMillis(600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ofMillis(600000L)) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build(); definitions.put("no_retry_1_params", settings); settings = RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(100L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelayDuration(Duration.ofMillis(60000L)) .setInitialRpcTimeoutDuration(Duration.ofMillis(600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ofMillis(600000L)) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build(); definitions.put("retry_policy_0_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); announceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); announceOperationSettings = OperationCallSettings.newBuilder(); deleteSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); deleteOperationSettings = OperationCallSettings.newBuilder(); getSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); insertSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); insertOperationSettings = OperationCallSettings.newBuilder(); listSettings = PagedCallSettings.newBuilder(LIST_PAGE_STR_FACT); patchSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); patchOperationSettings = OperationCallSettings.newBuilder(); withdrawSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); withdrawOperationSettings = OperationCallSettings.newBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( announceSettings, deleteSettings, getSettings, insertSettings, listSettings, patchSettings, withdrawSettings); initDefaults(this); } protected Builder(PublicAdvertisedPrefixesStubSettings settings) { super(settings); announceSettings = settings.announceSettings.toBuilder(); announceOperationSettings = settings.announceOperationSettings.toBuilder(); deleteSettings = settings.deleteSettings.toBuilder(); deleteOperationSettings = settings.deleteOperationSettings.toBuilder(); getSettings = settings.getSettings.toBuilder(); insertSettings = settings.insertSettings.toBuilder(); insertOperationSettings = settings.insertOperationSettings.toBuilder(); listSettings = settings.listSettings.toBuilder(); patchSettings = settings.patchSettings.toBuilder(); patchOperationSettings = settings.patchOperationSettings.toBuilder(); withdrawSettings = settings.withdrawSettings.toBuilder(); withdrawOperationSettings = settings.withdrawOperationSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( announceSettings, deleteSettings, getSettings, insertSettings, listSettings, patchSettings, withdrawSettings); } private static Builder createDefault() { Builder builder = new Builder(((ClientContext) null)); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .announceSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .deleteSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .getSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .insertSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .listSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .patchSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .withdrawSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .announceOperationSettings() .setInitialCallSettings( UnaryCallSettings .<AnnouncePublicAdvertisedPrefixeRequest, OperationSnapshot> newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); builder .deleteOperationSettings() .setInitialCallSettings( UnaryCallSettings .<DeletePublicAdvertisedPrefixeRequest, OperationSnapshot> newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); builder .insertOperationSettings() .setInitialCallSettings( UnaryCallSettings .<InsertPublicAdvertisedPrefixeRequest, OperationSnapshot> newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); builder .patchOperationSettings() .setInitialCallSettings( UnaryCallSettings .<PatchPublicAdvertisedPrefixeRequest, OperationSnapshot> newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); builder .withdrawOperationSettings() .setInitialCallSettings( UnaryCallSettings .<WithdrawPublicAdvertisedPrefixeRequest, OperationSnapshot> newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create(Operation.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create(Operation.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(500L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(20000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(600000L)) .build())); return builder; } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to announce. */ public UnaryCallSettings.Builder<AnnouncePublicAdvertisedPrefixeRequest, Operation> announceSettings() { return announceSettings; } /** Returns the builder for the settings used for calls to announce. */ public OperationCallSettings.Builder< AnnouncePublicAdvertisedPrefixeRequest, Operation, Operation> announceOperationSettings() { return announceOperationSettings; } /** Returns the builder for the settings used for calls to delete. */ public UnaryCallSettings.Builder<DeletePublicAdvertisedPrefixeRequest, Operation> deleteSettings() { return deleteSettings; } /** Returns the builder for the settings used for calls to delete. */ public OperationCallSettings.Builder<DeletePublicAdvertisedPrefixeRequest, Operation, Operation> deleteOperationSettings() { return deleteOperationSettings; } /** Returns the builder for the settings used for calls to get. */ public UnaryCallSettings.Builder<GetPublicAdvertisedPrefixeRequest, PublicAdvertisedPrefix> getSettings() { return getSettings; } /** Returns the builder for the settings used for calls to insert. */ public UnaryCallSettings.Builder<InsertPublicAdvertisedPrefixeRequest, Operation> insertSettings() { return insertSettings; } /** Returns the builder for the settings used for calls to insert. */ public OperationCallSettings.Builder<InsertPublicAdvertisedPrefixeRequest, Operation, Operation> insertOperationSettings() { return insertOperationSettings; } /** Returns the builder for the settings used for calls to list. */ public PagedCallSettings.Builder< ListPublicAdvertisedPrefixesRequest, PublicAdvertisedPrefixList, ListPagedResponse> listSettings() { return listSettings; } /** Returns the builder for the settings used for calls to patch. */ public UnaryCallSettings.Builder<PatchPublicAdvertisedPrefixeRequest, Operation> patchSettings() { return patchSettings; } /** Returns the builder for the settings used for calls to patch. */ public OperationCallSettings.Builder<PatchPublicAdvertisedPrefixeRequest, Operation, Operation> patchOperationSettings() { return patchOperationSettings; } /** Returns the builder for the settings used for calls to withdraw. */ public UnaryCallSettings.Builder<WithdrawPublicAdvertisedPrefixeRequest, Operation> withdrawSettings() { return withdrawSettings; } /** Returns the builder for the settings used for calls to withdraw. */ public OperationCallSettings.Builder< WithdrawPublicAdvertisedPrefixeRequest, Operation, Operation> withdrawOperationSettings() { return withdrawOperationSettings; } @Override public PublicAdvertisedPrefixesStubSettings build() throws IOException { return new PublicAdvertisedPrefixesStubSettings(this); } } }
apache/harmony
37,070
classlib/modules/awt/src/main/java/unix/org/apache/harmony/awt/wtk/linux/KeyCodeTranslator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Dmitry A. Durnev */ package org.apache.harmony.awt.wtk.linux; import java.awt.event.KeyEvent; import java.util.HashMap; import java.util.Map; import org.apache.harmony.awt.nativebridge.CLongPointer; import org.apache.harmony.awt.nativebridge.Int8Pointer; import org.apache.harmony.awt.nativebridge.NativeBridge; import org.apache.harmony.awt.nativebridge.linux.X11; import org.apache.harmony.awt.nativebridge.linux.X11Defs; import org.apache.harmony.awt.wtk.KeyInfo; final class KeyCodeTranslator { private static final NativeBridge bridge = NativeBridge.getInstance(); private static final X11 x11 = X11.getInstance(); private static final Map tableXK2VK; private static final Map tableVK2XK; static { tableXK2VK = new HashMap(); tableXK2VK.put(new Integer(X11Defs.XK_Tab), new Integer(KeyEvent.VK_TAB)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Tab), new Integer(KeyEvent.VK_TAB)); tableXK2VK.put(new Integer(X11Defs.XK_ISO_Left_Tab), new Integer(KeyEvent.VK_TAB)); tableXK2VK.put(new Integer(X11Defs.XK_Clear), new Integer(KeyEvent.VK_CLEAR)); tableXK2VK.put(new Integer(X11Defs.XK_Pause), new Integer(KeyEvent.VK_PAUSE)); tableXK2VK.put(new Integer(X11Defs.XK_Scroll_Lock), new Integer(KeyEvent.VK_SCROLL_LOCK)); tableXK2VK.put(new Integer(X11Defs.XK_Escape), new Integer(KeyEvent.VK_ESCAPE)); tableXK2VK.put(new Integer(X11Defs.XK_Delete), new Integer(KeyEvent.VK_DELETE)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Delete), new Integer(KeyEvent.VK_DELETE)); tableXK2VK.put(new Integer(X11Defs.XK_Kanji), new Integer(KeyEvent.VK_KANJI)); tableXK2VK.put(new Integer(X11Defs.XK_Hiragana), new Integer(KeyEvent.VK_HIRAGANA)); tableXK2VK.put(new Integer(X11Defs.XK_Katakana), new Integer(KeyEvent.VK_KATAKANA)); tableXK2VK.put(new Integer(X11Defs.XK_Kana_Lock), new Integer(KeyEvent.VK_KANA_LOCK)); tableXK2VK.put(new Integer(X11Defs.XK_Home), new Integer(KeyEvent.VK_HOME)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Home), new Integer(KeyEvent.VK_HOME)); tableXK2VK.put(new Integer(X11Defs.XK_Left), new Integer(KeyEvent.VK_LEFT)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Left), new Integer(KeyEvent.VK_LEFT)); tableXK2VK.put(new Integer(X11Defs.XK_Up), new Integer(KeyEvent.VK_UP)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Up), new Integer(KeyEvent.VK_UP)); tableXK2VK.put(new Integer(X11Defs.XK_Right), new Integer(KeyEvent.VK_RIGHT)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Right), new Integer(KeyEvent.VK_RIGHT)); tableXK2VK.put(new Integer(X11Defs.XK_Down), new Integer(KeyEvent.VK_DOWN)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Down), new Integer(KeyEvent.VK_DOWN)); tableXK2VK.put(new Integer(X11Defs.XK_Page_Up), new Integer(KeyEvent.VK_PAGE_UP)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Page_Up), new Integer(KeyEvent.VK_PAGE_UP)); tableXK2VK.put(new Integer(X11Defs.XK_Page_Down), new Integer(KeyEvent.VK_PAGE_DOWN)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Page_Down), new Integer(KeyEvent.VK_PAGE_DOWN)); tableXK2VK.put(new Integer(X11Defs.XK_End), new Integer(KeyEvent.VK_END)); tableXK2VK.put(new Integer(X11Defs.XK_KP_End), new Integer(KeyEvent.VK_END)); tableXK2VK.put(new Integer(X11Defs.XK_Insert), new Integer(KeyEvent.VK_INSERT)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Insert), new Integer(KeyEvent.VK_INSERT)); tableXK2VK.put(new Integer(X11Defs.XK_Undo), new Integer(KeyEvent.VK_UNDO)); tableXK2VK.put(new Integer(X11Defs.XK_Find), new Integer(KeyEvent.VK_FIND)); tableXK2VK.put(new Integer(X11Defs.XK_Cancel), new Integer(KeyEvent.VK_CANCEL)); tableXK2VK.put(new Integer(X11Defs.XK_Help), new Integer(KeyEvent.VK_HELP)); tableXK2VK.put(new Integer(X11Defs.XK_Num_Lock), new Integer(KeyEvent.VK_NUM_LOCK)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Left), new Integer(KeyEvent.VK_KP_LEFT)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Up), new Integer(KeyEvent.VK_KP_UP)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Right), new Integer(KeyEvent.VK_KP_RIGHT)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Down), new Integer(KeyEvent.VK_KP_DOWN)); tableXK2VK.put(new Integer(X11Defs.XK_KP_0), new Integer(KeyEvent.VK_NUMPAD0)); tableXK2VK.put(new Integer(X11Defs.XK_KP_1), new Integer(KeyEvent.VK_NUMPAD1)); tableXK2VK.put(new Integer(X11Defs.XK_KP_2), new Integer(KeyEvent.VK_NUMPAD2)); tableXK2VK.put(new Integer(X11Defs.XK_KP_3), new Integer(KeyEvent.VK_NUMPAD3)); tableXK2VK.put(new Integer(X11Defs.XK_KP_4), new Integer(KeyEvent.VK_NUMPAD4)); tableXK2VK.put(new Integer(X11Defs.XK_KP_5), new Integer(KeyEvent.VK_NUMPAD5)); tableXK2VK.put(new Integer(X11Defs.XK_KP_6), new Integer(KeyEvent.VK_NUMPAD6)); tableXK2VK.put(new Integer(X11Defs.XK_KP_7), new Integer(KeyEvent.VK_NUMPAD7)); tableXK2VK.put(new Integer(X11Defs.XK_KP_8), new Integer(KeyEvent.VK_NUMPAD8)); tableXK2VK.put(new Integer(X11Defs.XK_KP_9), new Integer(KeyEvent.VK_NUMPAD9)); tableXK2VK.put(new Integer(X11Defs.XK_F1), new Integer(KeyEvent.VK_F1)); tableXK2VK.put(new Integer(X11Defs.XK_KP_F1), new Integer(KeyEvent.VK_F1)); tableXK2VK.put(new Integer(X11Defs.XK_F2), new Integer(KeyEvent.VK_F2)); tableXK2VK.put(new Integer(X11Defs.XK_KP_F2), new Integer(KeyEvent.VK_F2)); tableXK2VK.put(new Integer(X11Defs.XK_F3), new Integer(KeyEvent.VK_F3)); tableXK2VK.put(new Integer(X11Defs.XK_KP_F3), new Integer(KeyEvent.VK_F3)); tableXK2VK.put(new Integer(X11Defs.XK_F4), new Integer(KeyEvent.VK_F4)); tableXK2VK.put(new Integer(X11Defs.XK_KP_F4), new Integer(KeyEvent.VK_F4)); tableXK2VK.put(new Integer(X11Defs.XK_F5), new Integer(KeyEvent.VK_F5)); tableXK2VK.put(new Integer(X11Defs.XK_F6), new Integer(KeyEvent.VK_F6)); tableXK2VK.put(new Integer(X11Defs.XK_F7), new Integer(KeyEvent.VK_F7)); tableXK2VK.put(new Integer(X11Defs.XK_F8), new Integer(KeyEvent.VK_F8)); tableXK2VK.put(new Integer(X11Defs.XK_F9), new Integer(KeyEvent.VK_F9)); tableXK2VK.put(new Integer(X11Defs.XK_F10), new Integer(KeyEvent.VK_F10)); tableXK2VK.put(new Integer(X11Defs.XK_F11), new Integer(KeyEvent.VK_F11)); tableXK2VK.put(new Integer(X11Defs.XK_F12), new Integer(KeyEvent.VK_F12)); tableXK2VK.put(new Integer(X11Defs.XK_F13), new Integer(KeyEvent.VK_F13)); tableXK2VK.put(new Integer(X11Defs.XK_F14), new Integer(KeyEvent.VK_F14)); tableXK2VK.put(new Integer(X11Defs.XK_F15), new Integer(KeyEvent.VK_F15)); tableXK2VK.put(new Integer(X11Defs.XK_F16), new Integer(KeyEvent.VK_F16)); tableXK2VK.put(new Integer(X11Defs.XK_F17), new Integer(KeyEvent.VK_F17)); tableXK2VK.put(new Integer(X11Defs.XK_F18), new Integer(KeyEvent.VK_F18)); tableXK2VK.put(new Integer(X11Defs.XK_F19), new Integer(KeyEvent.VK_F19)); tableXK2VK.put(new Integer(X11Defs.XK_F20), new Integer(KeyEvent.VK_F20)); tableXK2VK.put(new Integer(X11Defs.XK_F21), new Integer(KeyEvent.VK_F21)); tableXK2VK.put(new Integer(X11Defs.XK_F22), new Integer(KeyEvent.VK_F22)); tableXK2VK.put(new Integer(X11Defs.XK_F23), new Integer(KeyEvent.VK_F23)); tableXK2VK.put(new Integer(X11Defs.XK_F24), new Integer(KeyEvent.VK_F24)); tableXK2VK.put(new Integer(X11Defs.XK_Caps_Lock), new Integer(KeyEvent.VK_CAPS_LOCK)); tableXK2VK.put(new Integer(X11Defs.XK_dead_grave), new Integer(KeyEvent.VK_DEAD_GRAVE)); tableXK2VK.put(new Integer(X11Defs.XK_dead_acute), new Integer(KeyEvent.VK_DEAD_ACUTE)); tableXK2VK.put(new Integer(X11Defs.XK_dead_circumflex), new Integer(KeyEvent.VK_DEAD_CIRCUMFLEX)); tableXK2VK.put(new Integer(X11Defs.XK_dead_tilde), new Integer(KeyEvent.VK_DEAD_TILDE)); tableXK2VK.put(new Integer(X11Defs.XK_dead_macron), new Integer(KeyEvent.VK_DEAD_MACRON)); tableXK2VK.put(new Integer(X11Defs.XK_dead_breve), new Integer(KeyEvent.VK_DEAD_BREVE)); tableXK2VK.put(new Integer(X11Defs.XK_dead_abovedot), new Integer(KeyEvent.VK_DEAD_ABOVEDOT)); tableXK2VK.put(new Integer(X11Defs.XK_dead_diaeresis), new Integer(KeyEvent.VK_DEAD_DIAERESIS)); tableXK2VK.put(new Integer(X11Defs.XK_dead_abovering), new Integer(KeyEvent.VK_DEAD_ABOVERING)); tableXK2VK.put(new Integer(X11Defs.XK_dead_doubleacute), new Integer(KeyEvent.VK_DEAD_DOUBLEACUTE)); tableXK2VK.put(new Integer(X11Defs.XK_dead_caron), new Integer(KeyEvent.VK_DEAD_CARON)); tableXK2VK.put(new Integer(X11Defs.XK_dead_cedilla), new Integer(KeyEvent.VK_DEAD_CEDILLA)); tableXK2VK.put(new Integer(X11Defs.XK_dead_ogonek), new Integer(KeyEvent.VK_DEAD_OGONEK)); tableXK2VK.put(new Integer(X11Defs.XK_dead_iota), new Integer(KeyEvent.VK_DEAD_IOTA)); tableXK2VK.put(new Integer(X11Defs.XK_dead_voiced_sound), new Integer(KeyEvent.VK_DEAD_VOICED_SOUND)); tableXK2VK.put(new Integer(X11Defs.XK_dead_semivoiced_sound), new Integer(KeyEvent.VK_DEAD_SEMIVOICED_SOUND)); tableXK2VK.put(new Integer(X11Defs.XK_space), new Integer(KeyEvent.VK_SPACE)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Space), new Integer(KeyEvent.VK_SPACE)); tableXK2VK.put(new Integer(X11Defs.XK_quotedbl), new Integer(KeyEvent.VK_QUOTEDBL)); tableXK2VK.put(new Integer(X11Defs.XK_dollar), new Integer(KeyEvent.VK_DOLLAR)); tableXK2VK.put(new Integer(X11Defs.XK_ampersand), new Integer(KeyEvent.VK_AMPERSAND)); tableXK2VK.put(new Integer(X11Defs.XK_asterisk), new Integer(KeyEvent.VK_ASTERISK)); tableXK2VK.put(new Integer(X11Defs.XK_plus), new Integer(KeyEvent.VK_PLUS)); tableXK2VK.put(new Integer(X11Defs.XK_comma), new Integer(KeyEvent.VK_COMMA)); tableXK2VK.put(new Integer(X11Defs.XK_minus), new Integer(KeyEvent.VK_MINUS)); tableXK2VK.put(new Integer(X11Defs.XK_period), new Integer(KeyEvent.VK_PERIOD)); tableXK2VK.put(new Integer(X11Defs.XK_slash), new Integer(KeyEvent.VK_SLASH)); tableXK2VK.put(new Integer(X11Defs.XK_0), new Integer(KeyEvent.VK_0)); tableXK2VK.put(new Integer(X11Defs.XK_1), new Integer(KeyEvent.VK_1)); tableXK2VK.put(new Integer(X11Defs.XK_2), new Integer(KeyEvent.VK_2)); tableXK2VK.put(new Integer(X11Defs.XK_3), new Integer(KeyEvent.VK_3)); tableXK2VK.put(new Integer(X11Defs.XK_4), new Integer(KeyEvent.VK_4)); tableXK2VK.put(new Integer(X11Defs.XK_5), new Integer(KeyEvent.VK_5)); tableXK2VK.put(new Integer(X11Defs.XK_6), new Integer(KeyEvent.VK_6)); tableXK2VK.put(new Integer(X11Defs.XK_7), new Integer(KeyEvent.VK_7)); tableXK2VK.put(new Integer(X11Defs.XK_8), new Integer(KeyEvent.VK_8)); tableXK2VK.put(new Integer(X11Defs.XK_9), new Integer(KeyEvent.VK_9)); tableXK2VK.put(new Integer(X11Defs.XK_colon), new Integer(KeyEvent.VK_COLON)); tableXK2VK.put(new Integer(X11Defs.XK_semicolon), new Integer(KeyEvent.VK_SEMICOLON)); tableXK2VK.put(new Integer(X11Defs.XK_less), new Integer(KeyEvent.VK_LESS)); tableXK2VK.put(new Integer(X11Defs.XK_greater), new Integer(KeyEvent.VK_GREATER)); tableXK2VK.put(new Integer(X11Defs.XK_at), new Integer(KeyEvent.VK_AT)); tableXK2VK.put(new Integer(X11Defs.XK_A), new Integer(KeyEvent.VK_A)); tableXK2VK.put(new Integer(X11Defs.XK_B), new Integer(KeyEvent.VK_B)); tableXK2VK.put(new Integer(X11Defs.XK_C), new Integer(KeyEvent.VK_C)); tableXK2VK.put(new Integer(X11Defs.XK_D), new Integer(KeyEvent.VK_D)); tableXK2VK.put(new Integer(X11Defs.XK_E), new Integer(KeyEvent.VK_E)); tableXK2VK.put(new Integer(X11Defs.XK_F), new Integer(KeyEvent.VK_F)); tableXK2VK.put(new Integer(X11Defs.XK_G), new Integer(KeyEvent.VK_G)); tableXK2VK.put(new Integer(X11Defs.XK_H), new Integer(KeyEvent.VK_H)); tableXK2VK.put(new Integer(X11Defs.XK_I), new Integer(KeyEvent.VK_I)); tableXK2VK.put(new Integer(X11Defs.XK_J), new Integer(KeyEvent.VK_J)); tableXK2VK.put(new Integer(X11Defs.XK_K), new Integer(KeyEvent.VK_K)); tableXK2VK.put(new Integer(X11Defs.XK_L), new Integer(KeyEvent.VK_L)); tableXK2VK.put(new Integer(X11Defs.XK_M), new Integer(KeyEvent.VK_M)); tableXK2VK.put(new Integer(X11Defs.XK_N), new Integer(KeyEvent.VK_N)); tableXK2VK.put(new Integer(X11Defs.XK_O), new Integer(KeyEvent.VK_O)); tableXK2VK.put(new Integer(X11Defs.XK_P), new Integer(KeyEvent.VK_P)); tableXK2VK.put(new Integer(X11Defs.XK_Q), new Integer(KeyEvent.VK_Q)); tableXK2VK.put(new Integer(X11Defs.XK_R), new Integer(KeyEvent.VK_R)); tableXK2VK.put(new Integer(X11Defs.XK_S), new Integer(KeyEvent.VK_S)); tableXK2VK.put(new Integer(X11Defs.XK_T), new Integer(KeyEvent.VK_T)); tableXK2VK.put(new Integer(X11Defs.XK_U), new Integer(KeyEvent.VK_U)); tableXK2VK.put(new Integer(X11Defs.XK_V), new Integer(KeyEvent.VK_V)); tableXK2VK.put(new Integer(X11Defs.XK_W), new Integer(KeyEvent.VK_W)); tableXK2VK.put(new Integer(X11Defs.XK_X), new Integer(KeyEvent.VK_X)); tableXK2VK.put(new Integer(X11Defs.XK_Y), new Integer(KeyEvent.VK_Y)); tableXK2VK.put(new Integer(X11Defs.XK_Z), new Integer(KeyEvent.VK_Z)); tableXK2VK.put(new Integer(X11Defs.XK_underscore), new Integer(KeyEvent.VK_UNDERSCORE)); tableXK2VK.put(new Integer(X11Defs.XK_a), new Integer(KeyEvent.VK_A)); tableXK2VK.put(new Integer(X11Defs.XK_b), new Integer(KeyEvent.VK_B)); tableXK2VK.put(new Integer(X11Defs.XK_c), new Integer(KeyEvent.VK_C)); tableXK2VK.put(new Integer(X11Defs.XK_d), new Integer(KeyEvent.VK_D)); tableXK2VK.put(new Integer(X11Defs.XK_e), new Integer(KeyEvent.VK_E)); tableXK2VK.put(new Integer(X11Defs.XK_f), new Integer(KeyEvent.VK_F)); tableXK2VK.put(new Integer(X11Defs.XK_g), new Integer(KeyEvent.VK_G)); tableXK2VK.put(new Integer(X11Defs.XK_h), new Integer(KeyEvent.VK_H)); tableXK2VK.put(new Integer(X11Defs.XK_i), new Integer(KeyEvent.VK_I)); tableXK2VK.put(new Integer(X11Defs.XK_j), new Integer(KeyEvent.VK_J)); tableXK2VK.put(new Integer(X11Defs.XK_k), new Integer(KeyEvent.VK_K)); tableXK2VK.put(new Integer(X11Defs.XK_l), new Integer(KeyEvent.VK_L)); tableXK2VK.put(new Integer(X11Defs.XK_m), new Integer(KeyEvent.VK_M)); tableXK2VK.put(new Integer(X11Defs.XK_n), new Integer(KeyEvent.VK_N)); tableXK2VK.put(new Integer(X11Defs.XK_o), new Integer(KeyEvent.VK_O)); tableXK2VK.put(new Integer(X11Defs.XK_p), new Integer(KeyEvent.VK_P)); tableXK2VK.put(new Integer(X11Defs.XK_q), new Integer(KeyEvent.VK_Q)); tableXK2VK.put(new Integer(X11Defs.XK_r), new Integer(KeyEvent.VK_R)); tableXK2VK.put(new Integer(X11Defs.XK_s), new Integer(KeyEvent.VK_S)); tableXK2VK.put(new Integer(X11Defs.XK_t), new Integer(KeyEvent.VK_T)); tableXK2VK.put(new Integer(X11Defs.XK_u), new Integer(KeyEvent.VK_U)); tableXK2VK.put(new Integer(X11Defs.XK_v), new Integer(KeyEvent.VK_V)); tableXK2VK.put(new Integer(X11Defs.XK_w), new Integer(KeyEvent.VK_W)); tableXK2VK.put(new Integer(X11Defs.XK_x), new Integer(KeyEvent.VK_X)); tableXK2VK.put(new Integer(X11Defs.XK_y), new Integer(KeyEvent.VK_Y)); tableXK2VK.put(new Integer(X11Defs.XK_z), new Integer(KeyEvent.VK_Z)); tableXK2VK.put(new Integer(X11Defs.XK_braceleft), new Integer(KeyEvent.VK_BRACELEFT)); tableXK2VK.put(new Integer(X11Defs.XK_braceright), new Integer(KeyEvent.VK_BRACERIGHT)); tableXK2VK.put(new Integer(X11Defs.XK_multiply), new Integer(KeyEvent.VK_MULTIPLY)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Multiply), new Integer(KeyEvent.VK_MULTIPLY)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Decimal), new Integer(KeyEvent.VK_DECIMAL)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Divide), new Integer(KeyEvent.VK_DIVIDE)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Subtract), new Integer(KeyEvent.VK_SUBTRACT)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Separator), new Integer(KeyEvent.VK_SEPARATOR)); tableXK2VK.put(new Integer(X11Defs.XK_Meta_L), new Integer(KeyEvent.VK_META)); tableXK2VK.put(new Integer(X11Defs.XK_Meta_R), new Integer(KeyEvent.VK_META)); tableXK2VK.put(new Integer(X11Defs.XK_Alt_L), new Integer(KeyEvent.VK_ALT)); tableXK2VK.put(new Integer(X11Defs.XK_Alt_R), new Integer(KeyEvent.VK_ALT_GRAPH)); tableXK2VK.put(new Integer(X11Defs.XK_Shift_L), new Integer(KeyEvent.VK_SHIFT)); tableXK2VK.put(new Integer(X11Defs.XK_Shift_R), new Integer(KeyEvent.VK_SHIFT)); tableXK2VK.put(new Integer(X11Defs.XK_Control_L), new Integer(KeyEvent.VK_CONTROL)); tableXK2VK.put(new Integer(X11Defs.XK_Control_R), new Integer(KeyEvent.VK_CONTROL)); tableXK2VK.put(new Integer(X11Defs.XK_Return), new Integer(KeyEvent.VK_ENTER)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Enter), new Integer(KeyEvent.VK_ENTER)); tableXK2VK.put(new Integer(X11Defs.XK_equal), new Integer(KeyEvent.VK_EQUALS)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Equal), new Integer(KeyEvent.VK_EQUALS)); tableXK2VK.put(new Integer(X11Defs.XK_exclam), new Integer(KeyEvent.VK_EXCLAMATION_MARK)); tableXK2VK.put(new Integer(X11Defs.XK_exclamdown), new Integer(KeyEvent.VK_INVERTED_EXCLAMATION_MARK)); tableXK2VK.put(new Integer(X11Defs.XK_bracketright), new Integer(KeyEvent.VK_CLOSE_BRACKET)); tableXK2VK.put(new Integer(X11Defs.XK_bracketleft), new Integer(KeyEvent.VK_OPEN_BRACKET)); tableXK2VK.put(new Integer(X11Defs.XK_KP_Add), new Integer(KeyEvent.VK_ADD)); tableXK2VK.put(new Integer(X11Defs.XK_quoteright), new Integer(KeyEvent.VK_QUOTE)); tableXK2VK.put(new Integer(X11Defs.XK_quoteleft), new Integer(KeyEvent.VK_BACK_QUOTE)); tableXK2VK.put(new Integer(X11Defs.XK_Kana_Shift), new Integer(KeyEvent.VK_KANA)); tableXK2VK.put(new Integer(X11Defs.XK_MultipleCandidate), new Integer(KeyEvent.VK_ALL_CANDIDATES)); tableXK2VK.put(new Integer(X11Defs.XK_PreviousCandidate), new Integer(KeyEvent.VK_PREVIOUS_CANDIDATE)); tableXK2VK.put(new Integer(X11Defs.XK_backslash), new Integer(KeyEvent.VK_BACK_SLASH)); tableXK2VK.put(new Integer(X11Defs.XK_BackSpace), new Integer(KeyEvent.VK_BACK_SPACE)); tableXK2VK.put(new Integer(X11Defs.XK_asciicircum), new Integer(KeyEvent.VK_CIRCUMFLEX)); tableXK2VK.put(new Integer(X11Defs.XK_Codeinput), new Integer(KeyEvent.VK_CODE_INPUT)); tableXK2VK.put(new Integer(X11Defs.XK_EuroSign), new Integer(KeyEvent.VK_EURO_SIGN)); tableXK2VK.put(new Integer(X11Defs.XK_Hiragana), new Integer(KeyEvent.VK_JAPANESE_HIRAGANA)); tableXK2VK.put(new Integer(X11Defs.XK_Katakana), new Integer(KeyEvent.VK_JAPANESE_KATAKANA)); tableXK2VK.put(new Integer(X11Defs.XK_parenleft), new Integer(KeyEvent.VK_LEFT_PARENTHESIS)); tableXK2VK.put(new Integer(X11Defs.XK_parenright), new Integer(KeyEvent.VK_RIGHT_PARENTHESIS)); tableXK2VK.put(new Integer(X11Defs.XK_Mode_switch), new Integer(KeyEvent.VK_MODECHANGE)); tableXK2VK.put(new Integer(X11Defs.XK_numbersign), new Integer(KeyEvent.VK_NUMBER_SIGN)); tableXK2VK.put(new Integer(X11Defs.XK_percent), new Integer(KeyEvent.VK_5)); tableXK2VK.put(new Integer(X11Defs.XK_question), new Integer(KeyEvent.VK_SLASH)); tableXK2VK.put(new Integer(X11Defs.XK_bar), new Integer(KeyEvent.VK_BACK_SLASH)); tableVK2XK = new HashMap(); tableVK2XK.put(new Integer(KeyEvent.VK_TAB), new Integer(X11Defs.XK_Tab)); tableVK2XK.put(new Integer(KeyEvent.VK_CLEAR), new Integer(X11Defs.XK_Clear)); tableVK2XK.put(new Integer(KeyEvent.VK_PAUSE), new Integer(X11Defs.XK_Pause)); tableVK2XK.put(new Integer(KeyEvent.VK_SCROLL_LOCK), new Integer(X11Defs.XK_Scroll_Lock)); tableVK2XK.put(new Integer(KeyEvent.VK_ESCAPE), new Integer(X11Defs.XK_Escape)); tableVK2XK.put(new Integer(KeyEvent.VK_DELETE), new Integer(X11Defs.XK_Delete)); tableVK2XK.put(new Integer(KeyEvent.VK_KANJI), new Integer(X11Defs.XK_Kanji)); tableVK2XK.put(new Integer(KeyEvent.VK_HIRAGANA), new Integer(X11Defs.XK_Hiragana)); tableVK2XK.put(new Integer(KeyEvent.VK_KATAKANA), new Integer(X11Defs.XK_Katakana)); tableVK2XK.put(new Integer(KeyEvent.VK_KANA_LOCK), new Integer(X11Defs.XK_Kana_Lock)); tableVK2XK.put(new Integer(KeyEvent.VK_HOME), new Integer(X11Defs.XK_Home)); tableVK2XK.put(new Integer(KeyEvent.VK_LEFT), new Integer(X11Defs.XK_Left)); tableVK2XK.put(new Integer(KeyEvent.VK_UP), new Integer(X11Defs.XK_Up)); tableVK2XK.put(new Integer(KeyEvent.VK_RIGHT), new Integer(X11Defs.XK_Right)); tableVK2XK.put(new Integer(KeyEvent.VK_DOWN), new Integer(X11Defs.XK_Down)); tableVK2XK.put(new Integer(KeyEvent.VK_PAGE_UP), new Integer(X11Defs.XK_Page_Up)); tableVK2XK.put(new Integer(KeyEvent.VK_PAGE_DOWN), new Integer(X11Defs.XK_Page_Down)); tableVK2XK.put(new Integer(KeyEvent.VK_END), new Integer(X11Defs.XK_End)); tableVK2XK.put(new Integer(KeyEvent.VK_INSERT), new Integer(X11Defs.XK_Insert)); tableVK2XK.put(new Integer(KeyEvent.VK_UNDO), new Integer(X11Defs.XK_Undo)); tableVK2XK.put(new Integer(KeyEvent.VK_FIND), new Integer(X11Defs.XK_Find)); tableVK2XK.put(new Integer(KeyEvent.VK_CANCEL), new Integer(X11Defs.XK_Cancel)); tableVK2XK.put(new Integer(KeyEvent.VK_HELP), new Integer(X11Defs.XK_Help)); tableVK2XK.put(new Integer(KeyEvent.VK_NUM_LOCK), new Integer(X11Defs.XK_Num_Lock)); tableVK2XK.put(new Integer(KeyEvent.VK_F1), new Integer(X11Defs.XK_F1)); tableVK2XK.put(new Integer(KeyEvent.VK_F2), new Integer(X11Defs.XK_F2)); tableVK2XK.put(new Integer(KeyEvent.VK_F3), new Integer(X11Defs.XK_F3)); tableVK2XK.put(new Integer(KeyEvent.VK_F4), new Integer(X11Defs.XK_F4)); tableVK2XK.put(new Integer(KeyEvent.VK_F5), new Integer(X11Defs.XK_F5)); tableVK2XK.put(new Integer(KeyEvent.VK_F6), new Integer(X11Defs.XK_F6)); tableVK2XK.put(new Integer(KeyEvent.VK_F7), new Integer(X11Defs.XK_F7)); tableVK2XK.put(new Integer(KeyEvent.VK_F8), new Integer(X11Defs.XK_F8)); tableVK2XK.put(new Integer(KeyEvent.VK_F9), new Integer(X11Defs.XK_F9)); tableVK2XK.put(new Integer(KeyEvent.VK_F10), new Integer(X11Defs.XK_F10)); tableVK2XK.put(new Integer(KeyEvent.VK_F11), new Integer(X11Defs.XK_F11)); tableVK2XK.put(new Integer(KeyEvent.VK_F12), new Integer(X11Defs.XK_F12)); tableVK2XK.put(new Integer(KeyEvent.VK_F13), new Integer(X11Defs.XK_F13)); tableVK2XK.put(new Integer(KeyEvent.VK_F14), new Integer(X11Defs.XK_F14)); tableVK2XK.put(new Integer(KeyEvent.VK_F15), new Integer(X11Defs.XK_F15)); tableVK2XK.put(new Integer(KeyEvent.VK_F16), new Integer(X11Defs.XK_F16)); tableVK2XK.put(new Integer(KeyEvent.VK_F17), new Integer(X11Defs.XK_F17)); tableVK2XK.put(new Integer(KeyEvent.VK_F18), new Integer(X11Defs.XK_F18)); tableVK2XK.put(new Integer(KeyEvent.VK_F19), new Integer(X11Defs.XK_F19)); tableVK2XK.put(new Integer(KeyEvent.VK_F20), new Integer(X11Defs.XK_F20)); tableVK2XK.put(new Integer(KeyEvent.VK_F21), new Integer(X11Defs.XK_F21)); tableVK2XK.put(new Integer(KeyEvent.VK_F22), new Integer(X11Defs.XK_F22)); tableVK2XK.put(new Integer(KeyEvent.VK_F23), new Integer(X11Defs.XK_F23)); tableVK2XK.put(new Integer(KeyEvent.VK_F24), new Integer(X11Defs.XK_F24)); tableVK2XK.put(new Integer(KeyEvent.VK_CAPS_LOCK), new Integer(X11Defs.XK_Caps_Lock)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_GRAVE), new Integer(X11Defs.XK_dead_grave)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_ACUTE), new Integer(X11Defs.XK_dead_acute)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_CIRCUMFLEX), new Integer(X11Defs.XK_dead_circumflex)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_TILDE), new Integer(X11Defs.XK_dead_tilde)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_MACRON), new Integer(X11Defs.XK_dead_macron)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_BREVE), new Integer(X11Defs.XK_dead_breve)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_ABOVEDOT), new Integer(X11Defs.XK_dead_abovedot)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_DIAERESIS), new Integer(X11Defs.XK_dead_diaeresis)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_ABOVERING), new Integer(X11Defs.XK_dead_abovering)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_DOUBLEACUTE), new Integer(X11Defs.XK_dead_doubleacute)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_CARON), new Integer(X11Defs.XK_dead_caron)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_CEDILLA), new Integer(X11Defs.XK_dead_cedilla)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_OGONEK), new Integer(X11Defs.XK_dead_ogonek)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_IOTA), new Integer(X11Defs.XK_dead_iota)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_VOICED_SOUND), new Integer(X11Defs.XK_dead_voiced_sound)); tableVK2XK.put(new Integer(KeyEvent.VK_DEAD_SEMIVOICED_SOUND), new Integer(X11Defs.XK_dead_semivoiced_sound)); tableVK2XK.put(new Integer(KeyEvent.VK_SPACE), new Integer(X11Defs.XK_space)); tableVK2XK.put(new Integer(KeyEvent.VK_QUOTEDBL), new Integer(X11Defs.XK_quotedbl)); tableVK2XK.put(new Integer(KeyEvent.VK_DOLLAR), new Integer(X11Defs.XK_dollar)); tableVK2XK.put(new Integer(KeyEvent.VK_AMPERSAND), new Integer(X11Defs.XK_ampersand)); tableVK2XK.put(new Integer(KeyEvent.VK_ASTERISK), new Integer(X11Defs.XK_asterisk)); tableVK2XK.put(new Integer(KeyEvent.VK_PLUS), new Integer(X11Defs.XK_plus)); tableVK2XK.put(new Integer(KeyEvent.VK_COMMA), new Integer(X11Defs.XK_comma)); tableVK2XK.put(new Integer(KeyEvent.VK_MINUS), new Integer(X11Defs.XK_minus)); tableVK2XK.put(new Integer(KeyEvent.VK_PERIOD), new Integer(X11Defs.XK_period)); tableVK2XK.put(new Integer(KeyEvent.VK_SLASH), new Integer(X11Defs.XK_slash)); tableVK2XK.put(new Integer(KeyEvent.VK_0), new Integer(X11Defs.XK_0)); tableVK2XK.put(new Integer(KeyEvent.VK_1), new Integer(X11Defs.XK_1)); tableVK2XK.put(new Integer(KeyEvent.VK_2), new Integer(X11Defs.XK_2)); tableVK2XK.put(new Integer(KeyEvent.VK_3), new Integer(X11Defs.XK_3)); tableVK2XK.put(new Integer(KeyEvent.VK_4), new Integer(X11Defs.XK_4)); tableVK2XK.put(new Integer(KeyEvent.VK_5), new Integer(X11Defs.XK_5)); tableVK2XK.put(new Integer(KeyEvent.VK_6), new Integer(X11Defs.XK_6)); tableVK2XK.put(new Integer(KeyEvent.VK_7), new Integer(X11Defs.XK_7)); tableVK2XK.put(new Integer(KeyEvent.VK_8), new Integer(X11Defs.XK_8)); tableVK2XK.put(new Integer(KeyEvent.VK_9), new Integer(X11Defs.XK_9)); tableVK2XK.put(new Integer(KeyEvent.VK_COLON), new Integer(X11Defs.XK_colon)); tableVK2XK.put(new Integer(KeyEvent.VK_SEMICOLON), new Integer(X11Defs.XK_semicolon)); tableVK2XK.put(new Integer(KeyEvent.VK_LESS), new Integer(X11Defs.XK_less)); tableVK2XK.put(new Integer(KeyEvent.VK_GREATER), new Integer(X11Defs.XK_greater)); tableVK2XK.put(new Integer(KeyEvent.VK_AT), new Integer(X11Defs.XK_at)); tableVK2XK.put(new Integer(KeyEvent.VK_A), new Integer(X11Defs.XK_A)); tableVK2XK.put(new Integer(KeyEvent.VK_B), new Integer(X11Defs.XK_B)); tableVK2XK.put(new Integer(KeyEvent.VK_C), new Integer(X11Defs.XK_C)); tableVK2XK.put(new Integer(KeyEvent.VK_D), new Integer(X11Defs.XK_D)); tableVK2XK.put(new Integer(KeyEvent.VK_E), new Integer(X11Defs.XK_E)); tableVK2XK.put(new Integer(KeyEvent.VK_F), new Integer(X11Defs.XK_F)); tableVK2XK.put(new Integer(KeyEvent.VK_G), new Integer(X11Defs.XK_G)); tableVK2XK.put(new Integer(KeyEvent.VK_H), new Integer(X11Defs.XK_H)); tableVK2XK.put(new Integer(KeyEvent.VK_I), new Integer(X11Defs.XK_I)); tableVK2XK.put(new Integer(KeyEvent.VK_J), new Integer(X11Defs.XK_J)); tableVK2XK.put(new Integer(KeyEvent.VK_K), new Integer(X11Defs.XK_K)); tableVK2XK.put(new Integer(KeyEvent.VK_L), new Integer(X11Defs.XK_L)); tableVK2XK.put(new Integer(KeyEvent.VK_M), new Integer(X11Defs.XK_M)); tableVK2XK.put(new Integer(KeyEvent.VK_N), new Integer(X11Defs.XK_N)); tableVK2XK.put(new Integer(KeyEvent.VK_O), new Integer(X11Defs.XK_O)); tableVK2XK.put(new Integer(KeyEvent.VK_P), new Integer(X11Defs.XK_P)); tableVK2XK.put(new Integer(KeyEvent.VK_Q), new Integer(X11Defs.XK_Q)); tableVK2XK.put(new Integer(KeyEvent.VK_R), new Integer(X11Defs.XK_R)); tableVK2XK.put(new Integer(KeyEvent.VK_S), new Integer(X11Defs.XK_S)); tableVK2XK.put(new Integer(KeyEvent.VK_T), new Integer(X11Defs.XK_T)); tableVK2XK.put(new Integer(KeyEvent.VK_U), new Integer(X11Defs.XK_U)); tableVK2XK.put(new Integer(KeyEvent.VK_V), new Integer(X11Defs.XK_V)); tableVK2XK.put(new Integer(KeyEvent.VK_W), new Integer(X11Defs.XK_W)); tableVK2XK.put(new Integer(KeyEvent.VK_X), new Integer(X11Defs.XK_X)); tableVK2XK.put(new Integer(KeyEvent.VK_Y), new Integer(X11Defs.XK_Y)); tableVK2XK.put(new Integer(KeyEvent.VK_Z), new Integer(X11Defs.XK_Z)); tableVK2XK.put(new Integer(KeyEvent.VK_UNDERSCORE), new Integer(X11Defs.XK_underscore)); tableVK2XK.put(new Integer(KeyEvent.VK_BRACELEFT), new Integer(X11Defs.XK_braceleft)); tableVK2XK.put(new Integer(KeyEvent.VK_BRACERIGHT), new Integer(X11Defs.XK_braceright)); tableVK2XK.put(new Integer(KeyEvent.VK_MULTIPLY), new Integer(X11Defs.XK_multiply)); tableVK2XK.put(new Integer(KeyEvent.VK_DECIMAL), new Integer(X11Defs.XK_KP_Decimal)); tableVK2XK.put(new Integer(KeyEvent.VK_META), new Integer(X11Defs.XK_Meta_L)); tableVK2XK.put(new Integer(KeyEvent.VK_ALT), new Integer(X11Defs.XK_Alt_L)); tableVK2XK.put(new Integer(KeyEvent.VK_ALT_GRAPH), new Integer(X11Defs.XK_Alt_R)); tableVK2XK.put(new Integer(KeyEvent.VK_SHIFT), new Integer(X11Defs.XK_Shift_L)); tableVK2XK.put(new Integer(KeyEvent.VK_CONTROL), new Integer(X11Defs.XK_Control_L)); tableVK2XK.put(new Integer(KeyEvent.VK_ENTER), new Integer(X11Defs.XK_Return)); tableVK2XK.put(new Integer(KeyEvent.VK_EQUALS), new Integer(X11Defs.XK_equal)); tableVK2XK.put(new Integer(KeyEvent.VK_EXCLAMATION_MARK), new Integer(X11Defs.XK_exclam)); tableVK2XK.put(new Integer(KeyEvent.VK_INVERTED_EXCLAMATION_MARK), new Integer(X11Defs.XK_exclamdown)); tableVK2XK.put(new Integer(KeyEvent.VK_CLOSE_BRACKET), new Integer(X11Defs.XK_bracketright)); tableVK2XK.put(new Integer(KeyEvent.VK_OPEN_BRACKET), new Integer(X11Defs.XK_bracketleft)); tableVK2XK.put(new Integer(KeyEvent.VK_QUOTE), new Integer(X11Defs.XK_quoteright)); tableVK2XK.put(new Integer(KeyEvent.VK_BACK_QUOTE), new Integer(X11Defs.XK_quoteleft)); tableVK2XK.put(new Integer(KeyEvent.VK_KANA), new Integer(X11Defs.XK_Kana_Shift)); tableVK2XK.put(new Integer(KeyEvent.VK_ALL_CANDIDATES), new Integer(X11Defs.XK_MultipleCandidate)); tableVK2XK.put(new Integer(KeyEvent.VK_PREVIOUS_CANDIDATE), new Integer(X11Defs.XK_PreviousCandidate)); tableVK2XK.put(new Integer(KeyEvent.VK_BACK_SLASH), new Integer(X11Defs.XK_backslash)); tableVK2XK.put(new Integer(KeyEvent.VK_BACK_SPACE), new Integer(X11Defs.XK_BackSpace)); tableVK2XK.put(new Integer(KeyEvent.VK_CIRCUMFLEX), new Integer(X11Defs.XK_asciicircum)); tableVK2XK.put(new Integer(KeyEvent.VK_CODE_INPUT), new Integer(X11Defs.XK_Codeinput)); tableVK2XK.put(new Integer(KeyEvent.VK_EURO_SIGN), new Integer(X11Defs.XK_EuroSign)); tableVK2XK.put(new Integer(KeyEvent.VK_JAPANESE_HIRAGANA), new Integer(X11Defs.XK_Hiragana)); tableVK2XK.put(new Integer(KeyEvent.VK_JAPANESE_KATAKANA), new Integer(X11Defs.XK_Katakana)); tableVK2XK.put(new Integer(KeyEvent.VK_LEFT_PARENTHESIS), new Integer(X11Defs.XK_parenleft)); tableVK2XK.put(new Integer(KeyEvent.VK_RIGHT_PARENTHESIS), new Integer(X11Defs.XK_parenright)); tableVK2XK.put(new Integer(KeyEvent.VK_MODECHANGE), new Integer(X11Defs.XK_Mode_switch)); tableVK2XK.put(new Integer(KeyEvent.VK_NUMBER_SIGN), new Integer(X11Defs.XK_numbersign)); tableVK2XK.put(new Integer(KeyEvent.VK_UNDEFINED), new Integer(X11Defs.NoSymbol)); } /** * Translates virtual key to KeySym. * @param vk virtual key * @return KeySym or NoSymbol */ static int VK2XK(int vk) { Object xk = tableVK2XK.get(new Integer(vk)); if (xk != null) { return ((Integer)xk).intValue(); } return X11Defs.NoSymbol; } /** * Translates linux key event to internal structure KeyInfo and returns it. * @param event instance of XKeyEvent * @return instance of KeyInfo */ static KeyInfo translateEvent(X11.XKeyEvent event) { KeyInfo res = new KeyInfo(); int nBytes = 255; Int8Pointer buffer = bridge.createInt8Pointer(nBytes, false); buffer.fill((byte)0, nBytes); CLongPointer keySymPtr = bridge.createCLongPointer(1, false); nBytes = x11.XLookupString(event, buffer, nBytes, keySymPtr, null); if (nBytes > 0) { String str = buffer.getStringUTF(); res.keyChars.append(str); } else { res.keyChars.append(KeyEvent.CHAR_UNDEFINED); } int keySym = (int)keySymPtr.get(0); if (tableXK2VK.containsKey(new Integer(keySym))) { res.vKey = ((Integer) tableXK2VK.get(new Integer(keySym))).intValue(); res.keyLocation = deriveLocation(keySym); } else { res.vKey = KeyEvent.VK_UNDEFINED; res.keyLocation = KeyEvent.KEY_LOCATION_STANDARD; } return res; } private static int deriveLocation(int keySym) { switch (keySym) { case X11Defs.XK_Alt_L: case X11Defs.XK_Meta_L: case X11Defs.XK_Shift_L: case X11Defs.XK_Control_L: return KeyEvent.KEY_LOCATION_LEFT; case X11Defs.XK_Alt_R: case X11Defs.XK_Meta_R: case X11Defs.XK_Shift_R: case X11Defs.XK_Control_R: return KeyEvent.KEY_LOCATION_RIGHT; case X11Defs.XK_KP_Tab: case X11Defs.XK_KP_Delete: case X11Defs.XK_KP_Home: case X11Defs.XK_KP_Page_Up: case X11Defs.XK_KP_Page_Down: case X11Defs.XK_KP_End: case X11Defs.XK_KP_Insert: case X11Defs.XK_KP_Left: case X11Defs.XK_KP_Up: case X11Defs.XK_KP_Right: case X11Defs.XK_KP_Down: case X11Defs.XK_KP_0: case X11Defs.XK_KP_1: case X11Defs.XK_KP_2: case X11Defs.XK_KP_3: case X11Defs.XK_KP_4: case X11Defs.XK_KP_5: case X11Defs.XK_KP_6: case X11Defs.XK_KP_7: case X11Defs.XK_KP_8: case X11Defs.XK_KP_9: case X11Defs.XK_KP_F1: case X11Defs.XK_KP_F2: case X11Defs.XK_KP_F3: case X11Defs.XK_KP_F4: case X11Defs.XK_KP_Space: case X11Defs.XK_KP_Multiply: case X11Defs.XK_KP_Decimal: case X11Defs.XK_KP_Divide: case X11Defs.XK_KP_Subtract: case X11Defs.XK_KP_Separator: case X11Defs.XK_KP_Enter: case X11Defs.XK_KP_Equal: case X11Defs.XK_KP_Add: return KeyEvent.KEY_LOCATION_NUMPAD; default: return KeyEvent.KEY_LOCATION_STANDARD; } } }
apache/openjpa
36,406
openjpa-lib/src/main/java/org/apache/openjpa/lib/util/concurrent/ConcurrentReferenceHashMap.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.openjpa.lib.util.concurrent; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractMap; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import org.apache.openjpa.lib.util.ReferenceMap; import org.apache.openjpa.lib.util.SizedMap; import org.apache.openjpa.lib.util.collections.AbstractReferenceMap; /** * This class implements a HashMap which has limited synchronization * and reference keys or values(but not both). In particular mutators are * generally synchronized while accessors are generally not. Additionally the * Iterators returned by this class are not "fail-fast", but instead try to * continue to iterate over the data structure after changes have been * made. Finally purging of the reference queue is only done inside mutators. * Null keys are not supported if keys use references. Null values are not * supported if values use references. * This class is based heavily on the WeakHashMap class in the Java * collections package. */ public class ConcurrentReferenceHashMap extends AbstractMap implements ConcurrentMap, ReferenceMap, SizedMap, Cloneable { /** * Cache of random numbers used in "random" methods, since generating them * is expensive. We hope each map changes enough between cycling through * this list that the overall effect is random enough. */ static final double[] RANDOMS = new double[1000]; static { Random random = new Random(); for (int i = 0; i < RANDOMS.length; i++) RANDOMS[i] = random.nextDouble(); } /** * The hash table data. */ private transient Entry[] table; /** * The total number of entries in the hash table. */ private transient int count; /** * Rehashes the table when count exceeds this threshold. */ private int threshold; /** * The load factor for the HashMap. */ private float loadFactor; /** * The key reference type. */ private AbstractReferenceMap.ReferenceStrength keyType; /** * The value reference type. */ private AbstractReferenceMap.ReferenceStrength valueType; /** * Reference queue for cleared Entries */ private final ReferenceQueue queue = new ReferenceQueue(); /** * Spread "random" removes and iteration. */ private int randomEntry = 0; /** * Maximum entries. */ private int maxSize = Integer.MAX_VALUE; /** * Compare two objects. These might be keys, values, or Entry instances. * This implementation uses a normal null-safe object equality algorithm. * * @since 1.0.0 */ protected boolean eq(Object x, Object y) { return x == y || (x != null && x.equals(y)); } /** * Obtain the hashcode of an object. The object might be a key, a value, * or an Entry. This implementation just delegates to * {@link Object#hashCode} * * @since 1.0.0 */ protected int hc(Object o) { return o == null ? 0 : o.hashCode(); } /** * Constructs a new, empty HashMap with the specified initial * capacity and the specified load factor. * * @param keyType the reference type of map keys * @param valueType the reference type of map values * @param initialCapacity the initial capacity of the HashMap. * @param loadFactor a number between 0.0 and 1.0. * @throws IllegalArgumentException if neither keys nor values use hard * references, if the initial capacity is less than or equal to zero, or if * the load factor is less than or equal to zero */ public ConcurrentReferenceHashMap(AbstractReferenceMap.ReferenceStrength keyType, AbstractReferenceMap.ReferenceStrength valueType, int initialCapacity, float loadFactor) { if (initialCapacity < 0) { throw new IllegalArgumentException("Illegal Initial Capacity: " + initialCapacity); } if ((loadFactor > 1) || (loadFactor <= 0)) { throw new IllegalArgumentException("Illegal Load factor: " + loadFactor); } if (keyType != AbstractReferenceMap.ReferenceStrength.HARD && valueType != AbstractReferenceMap.ReferenceStrength.HARD) { throw new IllegalArgumentException("Either keys or values must " + "use hard references."); } this.keyType = keyType; this.valueType = valueType; this.loadFactor = loadFactor; table = new Entry[initialCapacity]; threshold = (int) (initialCapacity * loadFactor); } /** * Constructs a new, empty HashMap with the specified initial capacity * and default load factor. * * @param keyType the reference type of map keys * @param valueType the reference type of map values * @param initialCapacity the initial capacity of the HashMap. */ public ConcurrentReferenceHashMap(AbstractReferenceMap.ReferenceStrength keyType, AbstractReferenceMap.ReferenceStrength valueType, int initialCapacity) { this(keyType, valueType, initialCapacity, 0.75f); } /** * Constructs a new, empty HashMap with a default capacity and load factor. * * @param keyType the reference type of map keys * @param valueType the reference type of map values */ public ConcurrentReferenceHashMap(AbstractReferenceMap.ReferenceStrength keyType, AbstractReferenceMap.ReferenceStrength valueType) { this(keyType, valueType, 11, 0.75f); } /** * Constructs a new HashMap with the same mappings as the given * Map. The HashMap is created with a capacity of thrice the number * of entries in the given Map or 11 (whichever is greater), and a * default load factor. * * @param keyType the reference type of map keys * @param valueType the reference type of map values */ public ConcurrentReferenceHashMap(AbstractReferenceMap.ReferenceStrength keyType, AbstractReferenceMap.ReferenceStrength valueType, Map t) { this(keyType, valueType, Math.max(3 * t.size(), 11), 0.75f); putAll(t); } @Override public int getMaxSize() { return maxSize; } @Override public void setMaxSize(int maxSize) { this.maxSize = (maxSize < 0) ? Integer.MAX_VALUE : maxSize; if (this.maxSize != Integer.MAX_VALUE) removeOverflow(this.maxSize); } @Override public boolean isFull() { return maxSize != Integer.MAX_VALUE && size() >= maxSize; } @Override public void overflowRemoved(Object key, Object value) { } /** * Returns the number of key-value mappings in this Map. This * result is a snapshot, and may not reflect unprocessed entries * that will be removed before next attempted access because they * are no longer referenced. */ @Override public int size() { return count; } /** * Returns true if this Map contains no key-value mappings. This * result is a snapshot, and may not reflect unprocessed entries * that will be removed before next attempted access because they * are no longer referenced. */ @Override public boolean isEmpty() { return count == 0; } /** * Returns true if this HashMap maps one or more keys to the specified * value. * * @param value value whose presence in this Map is to be tested. */ @Override public boolean containsValue(Object value) { Entry[] tab = table; if (value == null) { if (valueType != AbstractReferenceMap.ReferenceStrength.HARD) return false; for (int i = tab.length; i-- > 0;) for (Entry e = tab[i]; e != null; e = e.getNext()) if (e.getValue() == null) return true; } else { for (int i = tab.length; i-- > 0;) for (Entry e = tab[i]; e != null; e = e.getNext()) if (eq(value, e.getValue())) return true; } return false; } /** * Returns true if this HashMap contains a mapping for the specified key. * * @param key key whose presence in this Map is to be tested. */ @Override public boolean containsKey(Object key) { if (key == null && keyType != AbstractReferenceMap.ReferenceStrength.HARD) return false; Entry[] tab = table; int hash = hc(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.getNext()) if (e.getHash() == hash && eq(key, e.getKey())) return true; return false; } /** * Returns the value to which this HashMap maps the specified key. * Returns null if the HashMap contains no mapping for this key. * * @param key key whose associated value is to be returned. */ @Override public Object get(Object key) { if (key == null && keyType != AbstractReferenceMap.ReferenceStrength.HARD) return null; Entry[] tab = table; int hash = hc(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.getNext()) if ((e.getHash() == hash) && eq(key, e.getKey())) return e.getValue(); return null; } /** * Rehashes the contents of the HashMap into a HashMap with a * larger capacity. This method is called automatically when the * number of keys in the HashMap exceeds this HashMap's capacity * and load factor. */ private void rehash() { int oldCapacity = table.length; Entry oldMap[] = table; int newCapacity = oldCapacity * 2 + 1; Entry newMap[] = new Entry[newCapacity]; for (int i = oldCapacity; i-- > 0;) { for (Entry old = oldMap[i]; old != null;) { if ((keyType != AbstractReferenceMap.ReferenceStrength.HARD && old.getKey() == null) || valueType != AbstractReferenceMap.ReferenceStrength.HARD && old.getValue() == null) { Entry e = old; old = old.getNext(); e.setNext(null); count--; } else { Entry e = (Entry) old.clone(queue); old = old.getNext(); int index = (e.getHash() & 0x7FFFFFFF) % newCapacity; e.setNext(newMap[index]); newMap[index] = e; } } } threshold = (int) (newCapacity * loadFactor); table = newMap; } /** * Associates the specified value with the specified key in this HashMap. * If the HashMap previously contained a mapping for this key, the old * value is replaced. * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @return previous value associated with specified key, or null if there * was no mapping for key. A null return can also indicate that * the HashMap previously associated null with the specified key. */ @Override public Object put(Object key, Object value) { if ((key == null && keyType != AbstractReferenceMap.ReferenceStrength.HARD) || (value == null && valueType != AbstractReferenceMap.ReferenceStrength.HARD)) throw new IllegalArgumentException("Null references not supported"); int hash = hc(key); synchronized (this) { expungeStaleEntries(); Entry[] tab = table; int index = 0; index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.getNext()) { if ((e.getHash() == hash) && eq(key, e.getKey())) { Object old = e.getValue(); if (valueType == AbstractReferenceMap.ReferenceStrength.HARD) e.setValue(value); else { e = newEntry(hash, e.getKey(), value, e.getNext()); if (prev == null) tab[index] = e; else prev.setNext(e); } return old; } } if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; index = (hash & 0x7FFFFFFF) % tab.length; } if (maxSize != Integer.MAX_VALUE) removeOverflow(maxSize - 1); tab[index] = newEntry(hash, key, value, tab[index]); count++; } return null; } /** * Creates a new entry. */ private Entry newEntry(int hash, Object key, Object value, Entry next) { AbstractReferenceMap.ReferenceStrength refType = (keyType != AbstractReferenceMap.ReferenceStrength.HARD) ? keyType : valueType; switch (refType) { case WEAK: return new WeakEntry(hash, key, value, refType == keyType, next, queue); case SOFT: return new SoftEntry(hash, key, value, refType == keyType, next, queue); default: return new HardEntry(hash, key, value, next); } } /** * Remove any entries equal to or over the max size. */ private void removeOverflow(int maxSize) { while (count > maxSize) { Map.Entry entry = removeRandom(); if (entry == null) break; overflowRemoved(entry.getKey(), entry.getValue()); } } /** * Removes the mapping for this key from this HashMap if present. * * @param key key whose mapping is to be removed from the Map. * @return previous value associated with specified key, or null if there * was no mapping for key. A null return can also indicate that * the HashMap previously associated null with the specified key. */ @Override public Object remove(Object key) { if (key == null && keyType != AbstractReferenceMap.ReferenceStrength.HARD) return null; int hash = hc(key); synchronized (this) { expungeStaleEntries(); Entry[] tab = table; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.getNext()) { if ((e.getHash() == hash) && eq(key, e.getKey())) { if (prev != null) prev.setNext(e.getNext()); // otherwise put the bucket after us else tab[index] = e.getNext(); count--; return e.getValue(); } } } return null; } @Override public void removeExpired() { synchronized (this) { expungeStaleEntries(); } } @Override public void keyExpired(Object value) { } @Override public void valueExpired(Object key) { } /** * Return an arbitrary entry index. */ private int randomEntryIndex() { if (randomEntry == RANDOMS.length) randomEntry = 0; return (int) (RANDOMS[randomEntry++] * table.length); } @Override public Map.Entry removeRandom() { synchronized (this) { expungeStaleEntries(); if (count == 0) return null; int random = randomEntryIndex(); int index = findEntry(random, random % 2 == 0, false); if (index == -1) return null; Entry rem = table[index]; table[index] = rem.getNext(); count--; return rem; } } /** * Find the index of the entry nearest the given index, starting in the * given direction. */ private int findEntry(int start, boolean forward, boolean searchedOther) { if (forward) { for (int i = start; i < table.length; i++) if (table[i] != null) return i; return (searchedOther || start == 0) ? -1 : findEntry(start - 1, false, true); } else { for (int i = start; i >= 0; i--) if (table[i] != null) return i; return (searchedOther || start == table.length - 1) ? -1 : findEntry(start + 1, true, true); } } @Override public Iterator randomEntryIterator() { // pass index so calculated before iterator refs table, in case table // gets replace with a larger one return new HashIterator(ENTRIES, randomEntryIndex()); } /** * Copies all of the mappings from the specified Map to this HashMap * These mappings will replace any mappings that this HashMap had for any * of the keys currently in the specified Map. * * @param t Mappings to be stored in this Map. */ @Override public void putAll(Map t) { Iterator i = t.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); put(e.getKey(), e.getValue()); } } /** * Removes all mappings from this HashMap. */ @Override public synchronized void clear() { // clear out ref queue. We don't need to expunge entries // since table is getting cleared. while (queue.poll() != null) ; table = new Entry[table.length]; count = 0; // Allocation of array may have caused GC, which may have caused // additional entries to go stale. Removing these entries from // the reference queue will make them eligible for reclamation. while (queue.poll() != null) ; } /** * Returns a shallow copy of this HashMap. The keys and values * themselves are not cloned. */ @Override public synchronized Object clone() { try { expungeStaleEntries(); ConcurrentReferenceHashMap t = (ConcurrentReferenceHashMap) super.clone(); t.table = new Entry[table.length]; for (int i = table.length; i-- > 0;) { Entry e = table[i]; if (e != null) { t.table[i] = (Entry) e.clone(t.queue); e = e.getNext(); for (Entry k = t.table[i]; e != null; e = e.getNext()) { k.setNext((Entry) e.clone(t.queue)); k = k.getNext(); } } } t.keySet = null; t.entrySet = null; t.values = null; return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } // Views private transient Set keySet = null; private transient Set entrySet = null; private transient Collection values = null; /** * Returns a Set view of the keys contained in this HashMap. The Set is * backed by the HashMap, so changes to the HashMap are reflected in the * Set, and vice-versa. The Set supports element removal, which removes * the corresponding mapping from the HashMap, via the Iterator.remove, * Set.remove, removeAll retainAll, and clear operations. It does not * support the add or addAll operations. */ @Override public Set keySet() { if (keySet == null) { keySet = new java.util.AbstractSet() { @Override public Iterator iterator() { return new HashIterator(KEYS, table.length - 1); } @Override public int size() { return count; } @Override public boolean contains(Object o) { return containsKey(o); } @Override public boolean remove(Object o) { return ConcurrentReferenceHashMap.this.remove(o) != null; } @Override public void clear() { ConcurrentReferenceHashMap.this.clear(); } }; } return keySet; } /** * Returns a Collection view of the values contained in this HashMap. * The Collection is backed by the HashMap, so changes to the HashMap are * reflected in the Collection, and vice-versa. The Collection supports * element removal, which removes the corresponding mapping from the * HashMap, via the Iterator.remove, Collection.remove, removeAll, * retainAll and clear operations. It does not support the add or addAll * operations. */ @Override public Collection values() { if (values == null) { values = new java.util.AbstractCollection() { @Override public Iterator iterator() { return new HashIterator(VALUES, table.length - 1); } @Override public int size() { return count; } @Override public boolean contains(Object o) { return containsValue(o); } @Override public void clear() { ConcurrentReferenceHashMap.this.clear(); } }; } return values; } /** * Returns a Collection view of the mappings contained in this HashMap. * Each element in the returned collection is a Map.Entry. The Collection * is backed by the HashMap, so changes to the HashMap are reflected in the * Collection, and vice-versa. The Collection supports element removal, * which removes the corresponding mapping from the HashMap, via the * Iterator.remove, Collection.remove, removeAll, retainAll and clear * operations. It does not support the add or addAll operations. * * @see Map.Entry */ @Override public Set entrySet() { if (entrySet == null) { entrySet = new java.util.AbstractSet() { @Override public Iterator iterator() { return new HashIterator(ENTRIES, table.length - 1); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry) o; Object key = entry.getKey(); Entry[] tab = table; int hash = hc(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.getNext()) if (e.getHash() == hash && eq(e, entry)) return true; return false; } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry) o; Object key = entry.getKey(); synchronized (ConcurrentReferenceHashMap.this) { Entry[] tab = table; int hash = hc(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.getNext()) { if (e.getHash() == hash && eq(e, entry)) { if (prev != null) prev.setNext(e.getNext()); else tab[index] = e.getNext(); count--; return true; } } return false; } } @Override public int size() { return count; } @Override public void clear() { ConcurrentReferenceHashMap.this.clear(); } }; } return entrySet; } /** * Expunge stale entries from the table. */ private void expungeStaleEntries() { Object r; while ((r = queue.poll()) != null) { Entry entry = (Entry) r; int hash = entry.getHash(); Entry[] tab = table; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.getNext()) { if (e == entry) { if (prev != null) prev.setNext(e.getNext()); // otherwise put the bucket after us else tab[index] = e.getNext(); count--; if (keyType == AbstractReferenceMap.ReferenceStrength.HARD) valueExpired(e.getKey()); else keyExpired(e.getValue()); } } } } /** * HashMap collision list entry. */ private interface Entry extends Map.Entry { int getHash(); Entry getNext(); void setNext(Entry next); Object clone(ReferenceQueue queue); } /** * Hard entry. */ private class HardEntry implements Entry { private int hash; private Object key; private Object value; private Entry next; HardEntry(int hash, Object key, Object value, Entry next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } @Override public int getHash() { return hash; } @Override public Entry getNext() { return next; } @Override public void setNext(Entry next) { this.next = next; } @Override public Object clone(ReferenceQueue queue) { // It is the callers responsibility to set the next field // correctly. return new HardEntry(hash, key, value, null); } // Map.Entry Ops @Override public Object getKey() { return key; } @Override public Object getValue() { return value; } @Override public Object setValue(Object value) { Object oldValue = this.value; this.value = value; return oldValue; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object k1 = key; Object k2 = e.getKey(); return (k1 == null ? k2 == null : eq(k1, k2)) && (value == null ? e.getValue() == null : eq(value, e.getValue())); } @Override public int hashCode() { return hash ^ (value == null ? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value.toString(); } } /** * Weak entry. */ private class WeakEntry extends WeakReference implements Entry { private int hash; private Object hard; private boolean keyRef; private Entry next; WeakEntry(int hash, Object key, Object value, boolean keyRef, Entry next, ReferenceQueue queue) { super((keyRef) ? key : value, queue); this.hash = hash; this.hard = (keyRef) ? value : key; this.keyRef = keyRef; this.next = next; } @Override public int getHash() { return hash; } @Override public Entry getNext() { return next; } @Override public void setNext(Entry next) { this.next = next; } @Override public Object clone(ReferenceQueue queue) { // It is the callers responsibility to set the next field // correctly. return new WeakEntry(hash, getKey(), getValue(), keyRef, null, queue); } // Map.Entry Ops @Override public Object getKey() { return (keyRef) ? super.get() : hard; } @Override public Object getValue() { return (keyRef) ? hard : super.get(); } @Override public Object setValue(Object value) { if (!keyRef) throw new Error("Attempt to reset reference value."); Object oldValue = hard; hard = value; return oldValue; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; return eq(getKey(), e.getKey()) && eq(getValue(), e.getValue()); } @Override public int hashCode() { Object val = getValue(); return hash ^ (val == null ? 0 : val.hashCode()); } @Override public String toString() { return getKey() + "=" + getValue(); } } /** * Soft entry. */ private class SoftEntry extends SoftReference implements Entry { private int hash; private Object hard; private boolean keyRef; private Entry next; SoftEntry(int hash, Object key, Object value, boolean keyRef, Entry next, ReferenceQueue queue) { super((keyRef) ? key : value, queue); this.hash = hash; this.hard = (keyRef) ? value : key; this.keyRef = keyRef; this.next = next; } @Override public int getHash() { return hash; } @Override public Entry getNext() { return next; } @Override public void setNext(Entry next) { this.next = next; } @Override public Object clone(ReferenceQueue queue) { // It is the callers responsibility to set the next field // correctly. return new SoftEntry(hash, getKey(), getValue(), keyRef, null, queue); } // Map.Entry Ops @Override public Object getKey() { return (keyRef) ? super.get() : hard; } @Override public Object getValue() { return (keyRef) ? hard : super.get(); } @Override public Object setValue(Object value) { if (!keyRef) throw new Error("Attempt to reset reference value."); Object oldValue = hard; hard = value; return oldValue; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; return eq(getKey(), e.getKey()) && eq(getValue(), e.getValue()); } @Override public int hashCode() { Object val = getValue(); return hash ^ (val == null ? 0 : val.hashCode()); } @Override public String toString() { return getKey() + "=" + getValue(); } } // Types of Enumerations/Iterations private static final int KEYS = 0; private static final int VALUES = 1; private static final int ENTRIES = 2; /** * Map iterator. */ private class HashIterator implements Iterator { final Entry[] table = ConcurrentReferenceHashMap.this.table; final int type; int startIndex; int stopIndex = 0; int index; Entry entry = null; Entry lastReturned = null; HashIterator(int type, int startIndex) { this.type = type; this.startIndex = startIndex; index = startIndex; } @Override public boolean hasNext() { if (entry != null) { return true; } while (index >= stopIndex) { if ((entry = table[index--]) != null) { return true; } } if (stopIndex == 0) { index = table.length - 1; stopIndex = startIndex + 1; while (index >= stopIndex) { if ((entry = table[index--]) != null) { return true; } } } return false; } @Override public Object next() { if (!hasNext()) throw new NoSuchElementException(); Entry e = lastReturned = entry; entry = e.getNext(); return type == KEYS ? e.getKey() : (type == VALUES ? e.getValue() : e); } @Override public void remove() { if (lastReturned == null) throw new IllegalStateException(); synchronized (ConcurrentReferenceHashMap.this) { Entry[] tab = ConcurrentReferenceHashMap.this.table; int index = (lastReturned.getHash() & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.getNext()) { if (e == lastReturned) { if (prev == null) tab[index] = e.getNext(); else prev.setNext(e.getNext()); count--; lastReturned = null; return; } } throw new Error("Iterated off table when doing remove"); } } } int capacity() { return table.length; } float loadFactor() { return loadFactor; } }
googleapis/google-cloud-java
36,281
java-dialogflow/google-cloud-dialogflow/src/test/java/com/google/cloud/dialogflow/v2beta1/DocumentsClientHttpJsonTest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.v2beta1; import static com.google.cloud.dialogflow.v2beta1.DocumentsClient.ListDocumentsPagedResponse; import static com.google.cloud.dialogflow.v2beta1.DocumentsClient.ListLocationsPagedResponse; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.httpjson.GaxHttpJsonProperties; import com.google.api.gax.httpjson.testing.MockHttpService; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ApiException; import com.google.api.gax.rpc.ApiExceptionFactory; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.testing.FakeStatusCode; import com.google.cloud.dialogflow.v2beta1.stub.HttpJsonDocumentsStub; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.collect.Lists; import com.google.longrunning.Operation; import com.google.protobuf.Any; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import com.google.rpc.Status; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutionException; import javax.annotation.Generated; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @Generated("by gapic-generator-java") public class DocumentsClientHttpJsonTest { private static MockHttpService mockService; private static DocumentsClient client; @BeforeClass public static void startStaticServer() throws IOException { mockService = new MockHttpService( HttpJsonDocumentsStub.getMethodDescriptors(), DocumentsSettings.getDefaultEndpoint()); DocumentsSettings settings = DocumentsSettings.newHttpJsonBuilder() .setTransportChannelProvider( DocumentsSettings.defaultHttpJsonTransportProviderBuilder() .setHttpTransport(mockService) .build()) .setCredentialsProvider(NoCredentialsProvider.create()) .build(); client = DocumentsClient.create(settings); } @AfterClass public static void stopServer() { client.close(); } @Before public void setUp() {} @After public void tearDown() throws Exception { mockService.reset(); } @Test public void listDocumentsTest() throws Exception { Document responsesElement = Document.newBuilder().build(); ListDocumentsResponse expectedResponse = ListDocumentsResponse.newBuilder() .setNextPageToken("") .addAllDocuments(Arrays.asList(responsesElement)) .build(); mockService.addResponse(expectedResponse); KnowledgeBaseName parent = KnowledgeBaseName.ofProjectKnowledgeBaseName("[PROJECT]", "[KNOWLEDGE_BASE]"); ListDocumentsPagedResponse pagedListResponse = client.listDocuments(parent); List<Document> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getDocumentsList().get(0), resources.get(0)); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void listDocumentsExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { KnowledgeBaseName parent = KnowledgeBaseName.ofProjectKnowledgeBaseName("[PROJECT]", "[KNOWLEDGE_BASE]"); client.listDocuments(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listDocumentsTest2() throws Exception { Document responsesElement = Document.newBuilder().build(); ListDocumentsResponse expectedResponse = ListDocumentsResponse.newBuilder() .setNextPageToken("") .addAllDocuments(Arrays.asList(responsesElement)) .build(); mockService.addResponse(expectedResponse); String parent = "projects/project-8161/knowledgeBases/knowledgeBase-8161"; ListDocumentsPagedResponse pagedListResponse = client.listDocuments(parent); List<Document> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getDocumentsList().get(0), resources.get(0)); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void listDocumentsExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String parent = "projects/project-8161/knowledgeBases/knowledgeBase-8161"; client.listDocuments(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getDocumentTest() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); mockService.addResponse(expectedResponse); DocumentName name = DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"); Document actualResponse = client.getDocument(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getDocumentExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { DocumentName name = DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"); client.getDocument(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getDocumentTest2() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); mockService.addResponse(expectedResponse); String name = "projects/project-5854/knowledgeBases/knowledgeBase-5854/documents/document-5854"; Document actualResponse = client.getDocument(name); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getDocumentExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-5854/knowledgeBases/knowledgeBase-5854/documents/document-5854"; client.getDocument(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void createDocumentTest() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); Operation resultOperation = Operation.newBuilder() .setName("createDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); KnowledgeBaseName parent = KnowledgeBaseName.ofProjectKnowledgeBaseName("[PROJECT]", "[KNOWLEDGE_BASE]"); Document document = Document.newBuilder().build(); Document actualResponse = client.createDocumentAsync(parent, document).get(); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void createDocumentExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { KnowledgeBaseName parent = KnowledgeBaseName.ofProjectKnowledgeBaseName("[PROJECT]", "[KNOWLEDGE_BASE]"); Document document = Document.newBuilder().build(); client.createDocumentAsync(parent, document).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void createDocumentTest2() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); Operation resultOperation = Operation.newBuilder() .setName("createDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); String parent = "projects/project-8161/knowledgeBases/knowledgeBase-8161"; Document document = Document.newBuilder().build(); Document actualResponse = client.createDocumentAsync(parent, document).get(); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void createDocumentExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String parent = "projects/project-8161/knowledgeBases/knowledgeBase-8161"; Document document = Document.newBuilder().build(); client.createDocumentAsync(parent, document).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void importDocumentsTest() throws Exception { ImportDocumentsResponse expectedResponse = ImportDocumentsResponse.newBuilder().addAllWarnings(new ArrayList<Status>()).build(); Operation resultOperation = Operation.newBuilder() .setName("importDocumentsTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); ImportDocumentsRequest request = ImportDocumentsRequest.newBuilder() .setParent( KnowledgeBaseName.ofProjectKnowledgeBaseName("[PROJECT]", "[KNOWLEDGE_BASE]") .toString()) .setDocumentTemplate(ImportDocumentTemplate.newBuilder().build()) .setImportGcsCustomMetadata(true) .build(); ImportDocumentsResponse actualResponse = client.importDocumentsAsync(request).get(); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void importDocumentsExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { ImportDocumentsRequest request = ImportDocumentsRequest.newBuilder() .setParent( KnowledgeBaseName.ofProjectKnowledgeBaseName("[PROJECT]", "[KNOWLEDGE_BASE]") .toString()) .setDocumentTemplate(ImportDocumentTemplate.newBuilder().build()) .setImportGcsCustomMetadata(true) .build(); client.importDocumentsAsync(request).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void deleteDocumentTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("deleteDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); DocumentName name = DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"); client.deleteDocumentAsync(name).get(); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void deleteDocumentExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { DocumentName name = DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"); client.deleteDocumentAsync(name).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void deleteDocumentTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("deleteDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); String name = "projects/project-5854/knowledgeBases/knowledgeBase-5854/documents/document-5854"; client.deleteDocumentAsync(name).get(); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void deleteDocumentExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-5854/knowledgeBases/knowledgeBase-5854/documents/document-5854"; client.deleteDocumentAsync(name).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void updateDocumentTest() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); Operation resultOperation = Operation.newBuilder() .setName("updateDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); Document document = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); Document actualResponse = client.updateDocumentAsync(document).get(); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void updateDocumentExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { Document document = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); client.updateDocumentAsync(document).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void updateDocumentTest2() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); Operation resultOperation = Operation.newBuilder() .setName("updateDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); Document document = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); Document actualResponse = client.updateDocumentAsync(document, updateMask).get(); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void updateDocumentExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { Document document = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); FieldMask updateMask = FieldMask.newBuilder().build(); client.updateDocumentAsync(document, updateMask).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void reloadDocumentTest() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); Operation resultOperation = Operation.newBuilder() .setName("reloadDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); DocumentName name = DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"); GcsSource gcsSource = GcsSource.newBuilder().build(); Document actualResponse = client.reloadDocumentAsync(name, gcsSource).get(); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void reloadDocumentExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { DocumentName name = DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"); GcsSource gcsSource = GcsSource.newBuilder().build(); client.reloadDocumentAsync(name, gcsSource).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void reloadDocumentTest2() throws Exception { Document expectedResponse = Document.newBuilder() .setName( DocumentName.ofProjectKnowledgeBaseDocumentName( "[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]") .toString()) .setDisplayName("displayName1714148973") .setMimeType("mimeType-1392120434") .addAllKnowledgeTypes(new ArrayList<Document.KnowledgeType>()) .setEnableAutoReload(true) .setLatestReloadStatus(Document.ReloadStatus.newBuilder().build()) .putAllMetadata(new HashMap<String, String>()) .build(); Operation resultOperation = Operation.newBuilder() .setName("reloadDocumentTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockService.addResponse(resultOperation); String name = "projects/project-5854/knowledgeBases/knowledgeBase-5854/documents/document-5854"; GcsSource gcsSource = GcsSource.newBuilder().build(); Document actualResponse = client.reloadDocumentAsync(name, gcsSource).get(); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void reloadDocumentExceptionTest2() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { String name = "projects/project-5854/knowledgeBases/knowledgeBase-5854/documents/document-5854"; GcsSource gcsSource = GcsSource.newBuilder().build(); client.reloadDocumentAsync(name, gcsSource).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { } } @Test public void listLocationsTest() throws Exception { Location responsesElement = Location.newBuilder().build(); ListLocationsResponse expectedResponse = ListLocationsResponse.newBuilder() .setNextPageToken("") .addAllLocations(Arrays.asList(responsesElement)) .build(); mockService.addResponse(expectedResponse); ListLocationsRequest request = ListLocationsRequest.newBuilder() .setName("projects/project-3664") .setFilter("filter-1274492040") .setPageSize(883849137) .setPageToken("pageToken873572522") .build(); ListLocationsPagedResponse pagedListResponse = client.listLocations(request); List<Location> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getLocationsList().get(0), resources.get(0)); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void listLocationsExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { ListLocationsRequest request = ListLocationsRequest.newBuilder() .setName("projects/project-3664") .setFilter("filter-1274492040") .setPageSize(883849137) .setPageToken("pageToken873572522") .build(); client.listLocations(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getLocationTest() throws Exception { Location expectedResponse = Location.newBuilder() .setName("name3373707") .setLocationId("locationId1541836720") .setDisplayName("displayName1714148973") .putAllLabels(new HashMap<String, String>()) .setMetadata(Any.newBuilder().build()) .build(); mockService.addResponse(expectedResponse); GetLocationRequest request = GetLocationRequest.newBuilder() .setName("projects/project-9062/locations/location-9062") .build(); Location actualResponse = client.getLocation(request); Assert.assertEquals(expectedResponse, actualResponse); List<String> actualRequests = mockService.getRequestPaths(); Assert.assertEquals(1, actualRequests.size()); String apiClientHeaderKey = mockService .getRequestHeaders() .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey()) .iterator() .next(); Assert.assertTrue( GaxHttpJsonProperties.getDefaultApiClientHeaderPattern() .matcher(apiClientHeaderKey) .matches()); } @Test public void getLocationExceptionTest() throws Exception { ApiException exception = ApiExceptionFactory.createException( new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false); mockService.addException(exception); try { GetLocationRequest request = GetLocationRequest.newBuilder() .setName("projects/project-9062/locations/location-9062") .build(); client.getLocation(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } }
googleapis/google-cloud-java
36,362
java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/ListKeyEventsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/analytics/admin/v1alpha/analytics_admin.proto // Protobuf Java Version: 3.25.8 package com.google.analytics.admin.v1alpha; /** * * * <pre> * Response message for ListKeyEvents RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1alpha.ListKeyEventsResponse} */ public final class ListKeyEventsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.ListKeyEventsResponse) ListKeyEventsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListKeyEventsResponse.newBuilder() to construct. private ListKeyEventsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListKeyEventsResponse() { keyEvents_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListKeyEventsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListKeyEventsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListKeyEventsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.ListKeyEventsResponse.class, com.google.analytics.admin.v1alpha.ListKeyEventsResponse.Builder.class); } public static final int KEY_EVENTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.analytics.admin.v1alpha.KeyEvent> keyEvents_; /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ @java.lang.Override public java.util.List<com.google.analytics.admin.v1alpha.KeyEvent> getKeyEventsList() { return keyEvents_; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.analytics.admin.v1alpha.KeyEventOrBuilder> getKeyEventsOrBuilderList() { return keyEvents_; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ @java.lang.Override public int getKeyEventsCount() { return keyEvents_.size(); } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1alpha.KeyEvent getKeyEvents(int index) { return keyEvents_.get(index); } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ @java.lang.Override public com.google.analytics.admin.v1alpha.KeyEventOrBuilder getKeyEventsOrBuilder(int index) { return keyEvents_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < keyEvents_.size(); i++) { output.writeMessage(1, keyEvents_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < keyEvents_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, keyEvents_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.analytics.admin.v1alpha.ListKeyEventsResponse)) { return super.equals(obj); } com.google.analytics.admin.v1alpha.ListKeyEventsResponse other = (com.google.analytics.admin.v1alpha.ListKeyEventsResponse) obj; if (!getKeyEventsList().equals(other.getKeyEventsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getKeyEventsCount() > 0) { hash = (37 * hash) + KEY_EVENTS_FIELD_NUMBER; hash = (53 * hash) + getKeyEventsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.analytics.admin.v1alpha.ListKeyEventsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for ListKeyEvents RPC. * </pre> * * Protobuf type {@code google.analytics.admin.v1alpha.ListKeyEventsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.ListKeyEventsResponse) com.google.analytics.admin.v1alpha.ListKeyEventsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListKeyEventsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListKeyEventsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1alpha.ListKeyEventsResponse.class, com.google.analytics.admin.v1alpha.ListKeyEventsResponse.Builder.class); } // Construct using com.google.analytics.admin.v1alpha.ListKeyEventsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (keyEventsBuilder_ == null) { keyEvents_ = java.util.Collections.emptyList(); } else { keyEvents_ = null; keyEventsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.analytics.admin.v1alpha.AnalyticsAdminProto .internal_static_google_analytics_admin_v1alpha_ListKeyEventsResponse_descriptor; } @java.lang.Override public com.google.analytics.admin.v1alpha.ListKeyEventsResponse getDefaultInstanceForType() { return com.google.analytics.admin.v1alpha.ListKeyEventsResponse.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1alpha.ListKeyEventsResponse build() { com.google.analytics.admin.v1alpha.ListKeyEventsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1alpha.ListKeyEventsResponse buildPartial() { com.google.analytics.admin.v1alpha.ListKeyEventsResponse result = new com.google.analytics.admin.v1alpha.ListKeyEventsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.analytics.admin.v1alpha.ListKeyEventsResponse result) { if (keyEventsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { keyEvents_ = java.util.Collections.unmodifiableList(keyEvents_); bitField0_ = (bitField0_ & ~0x00000001); } result.keyEvents_ = keyEvents_; } else { result.keyEvents_ = keyEventsBuilder_.build(); } } private void buildPartial0(com.google.analytics.admin.v1alpha.ListKeyEventsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.analytics.admin.v1alpha.ListKeyEventsResponse) { return mergeFrom((com.google.analytics.admin.v1alpha.ListKeyEventsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1alpha.ListKeyEventsResponse other) { if (other == com.google.analytics.admin.v1alpha.ListKeyEventsResponse.getDefaultInstance()) return this; if (keyEventsBuilder_ == null) { if (!other.keyEvents_.isEmpty()) { if (keyEvents_.isEmpty()) { keyEvents_ = other.keyEvents_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureKeyEventsIsMutable(); keyEvents_.addAll(other.keyEvents_); } onChanged(); } } else { if (!other.keyEvents_.isEmpty()) { if (keyEventsBuilder_.isEmpty()) { keyEventsBuilder_.dispose(); keyEventsBuilder_ = null; keyEvents_ = other.keyEvents_; bitField0_ = (bitField0_ & ~0x00000001); keyEventsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getKeyEventsFieldBuilder() : null; } else { keyEventsBuilder_.addAllMessages(other.keyEvents_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.analytics.admin.v1alpha.KeyEvent m = input.readMessage( com.google.analytics.admin.v1alpha.KeyEvent.parser(), extensionRegistry); if (keyEventsBuilder_ == null) { ensureKeyEventsIsMutable(); keyEvents_.add(m); } else { keyEventsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.analytics.admin.v1alpha.KeyEvent> keyEvents_ = java.util.Collections.emptyList(); private void ensureKeyEventsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { keyEvents_ = new java.util.ArrayList<com.google.analytics.admin.v1alpha.KeyEvent>(keyEvents_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1alpha.KeyEvent, com.google.analytics.admin.v1alpha.KeyEvent.Builder, com.google.analytics.admin.v1alpha.KeyEventOrBuilder> keyEventsBuilder_; /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public java.util.List<com.google.analytics.admin.v1alpha.KeyEvent> getKeyEventsList() { if (keyEventsBuilder_ == null) { return java.util.Collections.unmodifiableList(keyEvents_); } else { return keyEventsBuilder_.getMessageList(); } } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public int getKeyEventsCount() { if (keyEventsBuilder_ == null) { return keyEvents_.size(); } else { return keyEventsBuilder_.getCount(); } } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public com.google.analytics.admin.v1alpha.KeyEvent getKeyEvents(int index) { if (keyEventsBuilder_ == null) { return keyEvents_.get(index); } else { return keyEventsBuilder_.getMessage(index); } } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder setKeyEvents(int index, com.google.analytics.admin.v1alpha.KeyEvent value) { if (keyEventsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureKeyEventsIsMutable(); keyEvents_.set(index, value); onChanged(); } else { keyEventsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder setKeyEvents( int index, com.google.analytics.admin.v1alpha.KeyEvent.Builder builderForValue) { if (keyEventsBuilder_ == null) { ensureKeyEventsIsMutable(); keyEvents_.set(index, builderForValue.build()); onChanged(); } else { keyEventsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder addKeyEvents(com.google.analytics.admin.v1alpha.KeyEvent value) { if (keyEventsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureKeyEventsIsMutable(); keyEvents_.add(value); onChanged(); } else { keyEventsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder addKeyEvents(int index, com.google.analytics.admin.v1alpha.KeyEvent value) { if (keyEventsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureKeyEventsIsMutable(); keyEvents_.add(index, value); onChanged(); } else { keyEventsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder addKeyEvents( com.google.analytics.admin.v1alpha.KeyEvent.Builder builderForValue) { if (keyEventsBuilder_ == null) { ensureKeyEventsIsMutable(); keyEvents_.add(builderForValue.build()); onChanged(); } else { keyEventsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder addKeyEvents( int index, com.google.analytics.admin.v1alpha.KeyEvent.Builder builderForValue) { if (keyEventsBuilder_ == null) { ensureKeyEventsIsMutable(); keyEvents_.add(index, builderForValue.build()); onChanged(); } else { keyEventsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder addAllKeyEvents( java.lang.Iterable<? extends com.google.analytics.admin.v1alpha.KeyEvent> values) { if (keyEventsBuilder_ == null) { ensureKeyEventsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, keyEvents_); onChanged(); } else { keyEventsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder clearKeyEvents() { if (keyEventsBuilder_ == null) { keyEvents_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { keyEventsBuilder_.clear(); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public Builder removeKeyEvents(int index) { if (keyEventsBuilder_ == null) { ensureKeyEventsIsMutable(); keyEvents_.remove(index); onChanged(); } else { keyEventsBuilder_.remove(index); } return this; } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public com.google.analytics.admin.v1alpha.KeyEvent.Builder getKeyEventsBuilder(int index) { return getKeyEventsFieldBuilder().getBuilder(index); } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public com.google.analytics.admin.v1alpha.KeyEventOrBuilder getKeyEventsOrBuilder(int index) { if (keyEventsBuilder_ == null) { return keyEvents_.get(index); } else { return keyEventsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public java.util.List<? extends com.google.analytics.admin.v1alpha.KeyEventOrBuilder> getKeyEventsOrBuilderList() { if (keyEventsBuilder_ != null) { return keyEventsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(keyEvents_); } } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public com.google.analytics.admin.v1alpha.KeyEvent.Builder addKeyEventsBuilder() { return getKeyEventsFieldBuilder() .addBuilder(com.google.analytics.admin.v1alpha.KeyEvent.getDefaultInstance()); } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public com.google.analytics.admin.v1alpha.KeyEvent.Builder addKeyEventsBuilder(int index) { return getKeyEventsFieldBuilder() .addBuilder(index, com.google.analytics.admin.v1alpha.KeyEvent.getDefaultInstance()); } /** * * * <pre> * The requested Key Events * </pre> * * <code>repeated .google.analytics.admin.v1alpha.KeyEvent key_events = 1;</code> */ public java.util.List<com.google.analytics.admin.v1alpha.KeyEvent.Builder> getKeyEventsBuilderList() { return getKeyEventsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1alpha.KeyEvent, com.google.analytics.admin.v1alpha.KeyEvent.Builder, com.google.analytics.admin.v1alpha.KeyEventOrBuilder> getKeyEventsFieldBuilder() { if (keyEventsBuilder_ == null) { keyEventsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.analytics.admin.v1alpha.KeyEvent, com.google.analytics.admin.v1alpha.KeyEvent.Builder, com.google.analytics.admin.v1alpha.KeyEventOrBuilder>( keyEvents_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); keyEvents_ = null; } return keyEventsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.ListKeyEventsResponse) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.ListKeyEventsResponse) private static final com.google.analytics.admin.v1alpha.ListKeyEventsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.ListKeyEventsResponse(); } public static com.google.analytics.admin.v1alpha.ListKeyEventsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListKeyEventsResponse> PARSER = new com.google.protobuf.AbstractParser<ListKeyEventsResponse>() { @java.lang.Override public ListKeyEventsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListKeyEventsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListKeyEventsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1alpha.ListKeyEventsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
hibernate/hibernate-orm
34,474
hibernate-core/src/main/java/org/hibernate/mapping/SimpleValue.java
/* * SPDX-License-Identifier: Apache-2.0 * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.mapping; import java.io.Serializable; import java.lang.annotation.Annotation; import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.hibernate.AssertionFailure; import org.hibernate.FetchMode; import org.hibernate.Internal; import org.hibernate.MappingException; import org.hibernate.boot.spi.BootstrapContext; import org.hibernate.type.TimeZoneStorageStrategy; import org.hibernate.annotations.OnDeleteAction; import org.hibernate.boot.model.convert.internal.ConverterDescriptors; import org.hibernate.boot.model.convert.spi.ConverterDescriptor; import org.hibernate.boot.model.convert.spi.JpaAttributeConverterCreationContext; import org.hibernate.boot.model.internal.AnnotatedJoinColumns; import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.SqlStringGenerationContext; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.registry.classloading.spi.ClassLoadingException; import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.dialect.Dialect; import org.hibernate.generator.Generator; import org.hibernate.generator.GeneratorCreationContext; import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.TypeDetails; import org.hibernate.resource.beans.spi.ManagedBeanRegistry; import org.hibernate.service.ServiceRegistry; import org.hibernate.type.Type; import org.hibernate.type.descriptor.JdbcTypeNameMapper; import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.jdbc.JdbcType; import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators; import org.hibernate.type.internal.ConvertedBasicTypeImpl; import org.hibernate.type.internal.ParameterizedTypeImpl; import org.hibernate.type.MappingContext; import org.hibernate.type.spi.TypeConfiguration; import org.hibernate.usertype.DynamicParameterizedType; import jakarta.persistence.AttributeConverter; import org.hibernate.usertype.DynamicParameterizedType.ParameterType; import static java.lang.Boolean.parseBoolean; import static org.hibernate.boot.model.convert.spi.ConverterDescriptor.TYPE_NAME_PREFIX; import static org.hibernate.boot.model.internal.GeneratorBinder.ASSIGNED_GENERATOR_NAME; import static org.hibernate.boot.model.internal.GeneratorBinder.ASSIGNED_IDENTIFIER_GENERATOR_CREATOR; import static org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl.fromExplicit; import static org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass; import static org.hibernate.internal.util.collections.ArrayHelper.toBooleanArray; import static org.hibernate.mapping.MappingHelper.classForName; import static org.hibernate.models.spi.TypeDetails.Kind.PARAMETERIZED_TYPE; import static org.hibernate.type.descriptor.jdbc.LobTypeMappings.getLobCodeTypeMapping; import static org.hibernate.type.descriptor.jdbc.LobTypeMappings.isMappedToKnownLobCode; import static org.hibernate.type.descriptor.jdbc.NationalizedTypeMappings.toNationalizedTypeCode; /** * A mapping model object that represents any value that maps to columns. * * @author Gavin King * @author Yanming Zhou */ public abstract class SimpleValue implements KeyValue { @Deprecated(since = "7.0", forRemoval = true) public static final String DEFAULT_ID_GEN_STRATEGY = ASSIGNED_GENERATOR_NAME; private final MetadataBuildingContext buildingContext; private final MetadataImplementor metadata; private final List<Selectable> columns = new ArrayList<>(); private final List<Boolean> insertability = new ArrayList<>(); private final List<Boolean> updatability = new ArrayList<>(); private boolean partitionKey; private String typeName; private Properties typeParameters; private boolean isVersion; private boolean isNationalized; private boolean isLob; private NullValueSemantic nullValueSemantic; private String nullValue; private Table table; private String foreignKeyName; private String foreignKeyDefinition; private String foreignKeyOptions; private boolean alternateUniqueKey; private OnDeleteAction onDeleteAction; private boolean foreignKeyEnabled = true; private ConverterDescriptor<?,?> attributeConverterDescriptor; private Type type; private GeneratorCreator customIdGeneratorCreator = ASSIGNED_IDENTIFIER_GENERATOR_CREATOR; public SimpleValue(MetadataBuildingContext buildingContext) { this.buildingContext = buildingContext; this.metadata = buildingContext.getMetadataCollector(); } public SimpleValue(MetadataBuildingContext buildingContext, Table table) { this( buildingContext ); this.table = table; } protected SimpleValue(SimpleValue original) { this.buildingContext = original.buildingContext; this.metadata = original.metadata; this.columns.addAll( original.columns ); this.insertability.addAll( original.insertability ); this.updatability.addAll( original.updatability ); this.partitionKey = original.partitionKey; this.typeName = original.typeName; this.typeParameters = original.typeParameters == null ? null : new Properties( original.typeParameters ); this.isVersion = original.isVersion; this.isNationalized = original.isNationalized; this.isLob = original.isLob; this.nullValue = original.nullValue; this.table = original.table; this.foreignKeyName = original.foreignKeyName; this.foreignKeyDefinition = original.foreignKeyDefinition; this.foreignKeyEnabled = original.foreignKeyEnabled; this.alternateUniqueKey = original.alternateUniqueKey; this.onDeleteAction = original.onDeleteAction; this.attributeConverterDescriptor = original.attributeConverterDescriptor; this.type = original.type; this.customIdGeneratorCreator = original.customIdGeneratorCreator; this.nullValueSemantic = original.nullValueSemantic; this.foreignKeyOptions = original.foreignKeyOptions; } @Override public MetadataBuildingContext getBuildingContext() { return buildingContext; } BootstrapContext getBootstrapContext() { return getBuildingContext().getBootstrapContext(); } public MetadataImplementor getMetadata() { return metadata; } InFlightMetadataCollector getMetadataCollector() { return getBuildingContext().getMetadataCollector(); } @Override public ServiceRegistry getServiceRegistry() { return getMetadata().getMetadataBuildingOptions().getServiceRegistry(); } public TypeConfiguration getTypeConfiguration() { return getBootstrapContext().getTypeConfiguration(); } public void setOnDeleteAction(OnDeleteAction onDeleteAction) { this.onDeleteAction = onDeleteAction; } public OnDeleteAction getOnDeleteAction() { return onDeleteAction; } @Override public boolean isCascadeDeleteEnabled() { return onDeleteAction == OnDeleteAction.CASCADE; } public void addColumn(Column column) { addColumn( column, true, true ); } public void addColumn(Column column, boolean isInsertable, boolean isUpdatable) { justAddColumn( column, isInsertable, isUpdatable ); column.setValue( this ); column.setTypeIndex( columns.size() - 1 ); } public void addFormula(Formula formula) { justAddFormula( formula ); } protected void justAddColumn(Column column) { justAddColumn( column, true, true ); } protected void justAddColumn(Column column, boolean insertable, boolean updatable) { final int index = columns.indexOf( column ); if ( index == -1 ) { columns.add( column ); insertability.add( insertable ); updatability.add( updatable ); } else { if ( insertability.get( index ) != insertable ) { throw new IllegalStateException( "Same column is added more than once with different values for isInsertable" ); } if ( updatability.get( index ) != updatable ) { throw new IllegalStateException( "Same column is added more than once with different values for isUpdatable" ); } } } protected void justAddFormula(Formula formula) { columns.add( formula ); insertability.add( false ); updatability.add( false ); } public void sortColumns(int[] originalOrder) { if ( columns.size() > 1 ) { final var originalColumns = columns.toArray( new Selectable[0] ); final boolean[] originalInsertability = toBooleanArray( insertability ); final boolean[] originalUpdatability = toBooleanArray( updatability ); for ( int i = 0; i < originalOrder.length; i++ ) { final int originalIndex = originalOrder[i]; final var selectable = originalColumns[i]; if ( selectable instanceof Column column ) { column.setTypeIndex( originalIndex ); } columns.set( originalIndex, selectable ); insertability.set( originalIndex, originalInsertability[i] ); updatability.set( originalIndex, originalUpdatability[i] ); } } } @Override public boolean hasFormula() { for ( var selectable : getSelectables() ) { if ( selectable instanceof Formula ) { return true; } } return false; } @Override public int getColumnSpan() { return columns.size(); } protected Selectable getColumn(int position){ return columns.get( position ); } @Override public List<Selectable> getSelectables() { return columns; } @Override public List<Column> getColumns() { if ( hasFormula() ) { // in principle this method should never get called // if we have formulas in the mapping throw new AssertionFailure("value involves formulas"); } //noinspection unchecked, rawtypes return (List) columns; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { if ( typeName != null && typeName.startsWith( TYPE_NAME_PREFIX ) ) { setAttributeConverterDescriptor( typeName ); } else { this.typeName = typeName; } } void setAttributeConverterDescriptor(String typeName) { final String converterClassName = typeName.substring( TYPE_NAME_PREFIX.length() ); final var bootstrapContext = getBootstrapContext(); @SuppressWarnings("unchecked") // Completely safe final var clazz = (Class<? extends AttributeConverter<?,?>>) classForName( AttributeConverter.class, converterClassName, bootstrapContext ); attributeConverterDescriptor = ConverterDescriptors.of( clazz, null, false, bootstrapContext.getClassmateContext() ); } ClassLoaderService classLoaderService() { return getBootstrapContext().getClassLoaderService(); } public void makeVersion() { this.isVersion = true; } public boolean isVersion() { return isVersion; } public void makeNationalized() { this.isNationalized = true; } public boolean isNationalized() { return isNationalized; } public void makeLob() { this.isLob = true; } public boolean isLob() { return isLob; } public void setTable(Table table) { this.table = table; } @Override public void createForeignKey() throws MappingException {} public void createForeignKey(PersistentClass referencedEntity, AnnotatedJoinColumns joinColumns) {} @Override public ForeignKey createForeignKeyOfEntity(String entityName) { if ( isConstrained() ) { final var foreignKey = table.createForeignKey( getForeignKeyName(), getConstraintColumns(), entityName, getForeignKeyDefinition(), getForeignKeyOptions() ); foreignKey.setOnDeleteAction( onDeleteAction ); return foreignKey; } else { return null; } } @Override public ForeignKey createForeignKeyOfEntity(String entityName, List<Column> referencedColumns) { if ( isConstrained() ) { final var foreignKey = table.createForeignKey( getForeignKeyName(), getConstraintColumns(), entityName, getForeignKeyDefinition(), getForeignKeyOptions(), referencedColumns ); foreignKey.setOnDeleteAction( onDeleteAction ); return foreignKey; } return null; } @Override public void createUniqueKey(MetadataBuildingContext context) { if ( hasFormula() ) { throw new MappingException( "Unique key constraint involves formulas" ); } getTable().createUniqueKey( getConstraintColumns(), context ); } @Internal public void setCustomIdGeneratorCreator(GeneratorCreator customIdGeneratorCreator) { this.customIdGeneratorCreator = customIdGeneratorCreator; } @Internal public GeneratorCreator getCustomIdGeneratorCreator() { return customIdGeneratorCreator; } @Deprecated(since = "7.0", forRemoval = true) @Override @SuppressWarnings("removal") public Generator createGenerator(Dialect dialect, RootClass rootClass) { return createGenerator( dialect, rootClass, null, new GeneratorSettings() { @Override public String getDefaultCatalog() { return null; } @Override public String getDefaultSchema() { return null; } @Override public SqlStringGenerationContext getSqlStringGenerationContext() { final var database = buildingContext.getMetadataCollector().getDatabase(); return fromExplicit( database.getJdbcEnvironment(), database, getDefaultCatalog(), getDefaultSchema() ); } } ); } @Override public Generator createGenerator( Dialect dialect, RootClass rootClass, Property property, GeneratorSettings defaults) { if ( customIdGeneratorCreator != null ) { final var context = new IdGeneratorCreationContext( this, rootClass, property, defaults ); final var generator = customIdGeneratorCreator.createGenerator( context ); if ( generator.allowAssignedIdentifiers() && nullValue == null ) { setNullValueUndefined(); } return generator; } else { return null; } } @Internal public void setColumnToIdentity() { if ( getColumnSpan() != 1 ) { throw new MappingException( "Identity generation requires exactly one column" ); } else if ( getColumn(0) instanceof Column column ) { column.setIdentity( true ); } else { throw new MappingException( "Identity generation requires a column" ); } } @Override public boolean isUpdateable() { //needed to satisfy KeyValue return true; } @Override public FetchMode getFetchMode() { return FetchMode.SELECT; } @Override public Table getTable() { return table; } /** * The property or field value which indicates that field * or property has never been set. * * @see org.hibernate.engine.internal.UnsavedValueFactory * @see org.hibernate.engine.spi.IdentifierValue * @see org.hibernate.engine.spi.VersionValue */ @Override public String getNullValue() { return nullValue; } /** * Set the property or field value indicating that field * or property has never been set. * * @see org.hibernate.engine.internal.UnsavedValueFactory * @see org.hibernate.engine.spi.IdentifierValue * @see org.hibernate.engine.spi.VersionValue */ public void setNullValue(String nullValue) { nullValueSemantic = decodeNullValueSemantic( nullValue ); if ( nullValueSemantic == NullValueSemantic.VALUE ) { this.nullValue = nullValue; } } private static NullValueSemantic decodeNullValueSemantic(String nullValue) { return switch ( nullValue ) { // magical values (legacy of hbm.xml) case "null" -> NullValueSemantic.NULL; case "none" -> NullValueSemantic.NONE; case "any" -> NullValueSemantic.ANY; case "undefined" -> NullValueSemantic.UNDEFINED; default -> NullValueSemantic.VALUE; }; } /** * The rule for determining if the field or * property has been set. * * @see org.hibernate.engine.internal.UnsavedValueFactory */ @Override public NullValueSemantic getNullValueSemantic() { return nullValueSemantic; } /** * Specifies the rule for determining if the field or * property has been set. * * @see org.hibernate.engine.internal.UnsavedValueFactory */ public void setNullValueSemantic(NullValueSemantic nullValueSemantic) { this.nullValueSemantic = nullValueSemantic; } /** * Specifies that there is no well-defined property or * field value indicating that field or property has never * been set. * * @see org.hibernate.engine.internal.UnsavedValueFactory * @see org.hibernate.engine.spi.IdentifierValue#UNDEFINED * @see org.hibernate.engine.spi.VersionValue#UNDEFINED */ public void setNullValueUndefined() { nullValueSemantic = NullValueSemantic.UNDEFINED; } public String getForeignKeyName() { return foreignKeyName; } public void setForeignKeyName(String foreignKeyName) { this.foreignKeyName = foreignKeyName; } public boolean isForeignKeyEnabled() { return foreignKeyEnabled; } public void disableForeignKey() { this.foreignKeyEnabled = false; } public boolean isConstrained() { return isForeignKeyEnabled() && !hasFormula(); } public String getForeignKeyOptions() { return foreignKeyOptions; } public void setForeignKeyOptions(String foreignKeyOptions) { this.foreignKeyOptions = foreignKeyOptions; } public String getForeignKeyDefinition() { return foreignKeyDefinition; } public void setForeignKeyDefinition(String foreignKeyDefinition) { this.foreignKeyDefinition = foreignKeyDefinition; } @Override public boolean isAlternateUniqueKey() { return alternateUniqueKey; } public void setAlternateUniqueKey(boolean unique) { this.alternateUniqueKey = unique; } @Override public boolean isNullable() { for ( var selectable : getSelectables() ) { if ( selectable instanceof Formula ) { // if there are *any* formulas, then the Value overall is // considered nullable return true; } else if ( selectable instanceof Column column ) { if ( !column.isNullable() ) { // if there is a single non-nullable column, the Value // overall is considered non-nullable. return false; } } } // nullable by default return true; } @Override public boolean isSimpleValue() { return true; } @Override public boolean isValid(MappingContext mappingContext) throws MappingException { return getColumnSpan() == getType().getColumnSpan( mappingContext ); } protected void setAttributeConverterDescriptor(ConverterDescriptor<?,?> descriptor) { this.attributeConverterDescriptor = descriptor; } protected ConverterDescriptor<?,?> getAttributeConverterDescriptor() { return attributeConverterDescriptor; } @Override public void setTypeUsingReflection(String className, String propertyName) throws MappingException { // NOTE: this is called as the last piece in setting SimpleValue type information, // and implementations rely on that fact, using it as a signal that all // the information it is going to get is already specified at this point if ( typeName == null && type == null ) { if ( attributeConverterDescriptor == null ) { // This is here to work like legacy. This should change when we integrate with metamodel // to look for JdbcType and JavaType individually and create the BasicType (well, really // keep a registry of [JdbcType,JavaType] -> BasicType...) if ( className == null ) { throw new MappingException( "Attribute types for a dynamic entity must be explicitly specified: " + propertyName ); } typeName = getClass( className, propertyName ).getName(); // TODO: To fully support isNationalized here we need to do the process hinted at above // essentially, much of the logic from #buildAttributeConverterTypeAdapter wrt // resolving a (1) JdbcType, a (2) JavaType and dynamically building a BasicType // combining them. } else { // we had an AttributeConverter type = buildAttributeConverterTypeAdapter(); } } // otherwise assume either // (a) explicit type was specified or // (b) determine was already performed } private Class<?> getClass(String className, String propertyName) { return reflectedPropertyClass( className, propertyName, classLoaderService() ); } /** * Build a Hibernate Type that incorporates the JPA AttributeConverter. AttributeConverter works totally in * memory, meaning it converts between one Java representation (the entity attribute representation) and another * (the value bound into JDBC statements or extracted from results). However, the Hibernate Type system operates * at the lower level of actually dealing directly with those JDBC objects. So even though we have an * AttributeConverter, we still need to "fill out" the rest of the BasicType data and bridge calls * to bind/extract through the converter. * <p> * Essentially the idea here is that an intermediate Java type needs to be used. Let's use an example as a means * to illustrate... Consider an {@code AttributeConverter<Integer,String>}. This tells Hibernate that the domain * model defines this attribute as an Integer value (the 'entityAttributeJavaType'), but that we need to treat the * value as a String (the 'databaseColumnJavaType') when dealing with JDBC (aka, the database type is a * VARCHAR/CHAR):<ul> * <li> * When binding values to PreparedStatements we need to convert the Integer value from the entity * into a String and pass that String to setString. The conversion is handled by calling * {@link AttributeConverter#convertToDatabaseColumn(Object)} * </li> * <li> * When extracting values from ResultSets (or CallableStatement parameters) we need to handle the * value via getString, and convert that returned String to an Integer. That conversion is handled * by calling {@link AttributeConverter#convertToEntityAttribute(Object)} * </li> * </ul> * * @return The built AttributeConverter -> Type adapter */ // @todo : ultimately I want to see attributeConverterJavaType and attributeConverterJdbcTypeCode specifiable separately // then we can "play them against each other" in terms of determining proper typing // @todo : see if we already have previously built a custom on-the-fly BasicType for this AttributeConverter; // see note below about caching private Type buildAttributeConverterTypeAdapter() { // todo : validate the number of columns present here? return buildAttributeConverterTypeAdapter( attributeConverterDescriptor.createJpaAttributeConverter( new JpaAttributeConverterCreationContext() { @Override public ManagedBeanRegistry getManagedBeanRegistry() { return getBootstrapContext().getManagedBeanRegistry(); } @Override public TypeConfiguration getTypeConfiguration() { return getMetadata().getTypeConfiguration(); } } ) ); } private <T> Type buildAttributeConverterTypeAdapter( JpaAttributeConverter<T, ?> jpaAttributeConverter) { final var domainJavaType = jpaAttributeConverter.getDomainJavaType(); final var relationalJavaType = jpaAttributeConverter.getRelationalJavaType(); // build the SqlTypeDescriptor adapter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Going back to the illustration, this should be a SqlTypeDescriptor that handles the Integer <-> String // conversions. This is the more complicated piece. First we need to determine the JDBC type code // corresponding to the AttributeConverter's declared "databaseColumnJavaType" (how we read that value out // of ResultSets). See JdbcTypeJavaClassMappings for details. Again, given example, this should return // VARCHAR/CHAR final var recommendedJdbcType = relationalJavaType.getRecommendedJdbcType( // todo (6.0) : handle the other JdbcRecommendedSqlTypeMappingContext methods new JdbcTypeIndicators() { @Override public TypeConfiguration getTypeConfiguration() { return metadata.getTypeConfiguration(); } @Override public TimeZoneStorageStrategy getDefaultTimeZoneStorageStrategy() { return buildingContext.getBuildingOptions().getDefaultTimeZoneStorage(); } @Override public Dialect getDialect() { return buildingContext.getMetadataCollector().getDatabase().getDialect(); } } ); // todo : cache the AttributeConverterTypeAdapter in case that AttributeConverter is applied multiple times. return new ConvertedBasicTypeImpl<>( TYPE_NAME_PREFIX + jpaAttributeConverter.getConverterJavaType().getTypeName(), String.format( "BasicType adapter for AttributeConverter<%s,%s>", domainJavaType.getTypeName(), relationalJavaType.getTypeName() ), metadata.getTypeConfiguration().getJdbcTypeRegistry() .getDescriptor( jdbcTypeCode( recommendedJdbcType, domainJavaType ) ), jpaAttributeConverter ); } private <T> int jdbcTypeCode(JdbcType recommendedJdbcType, JavaType<T> domainJavaType) { final int recommendedDdlTypeCode = recommendedJdbcType.getDdlTypeCode(); final int jdbcTypeCode; if ( isLob() ) { if ( isMappedToKnownLobCode( recommendedDdlTypeCode ) ) { jdbcTypeCode = getLobCodeTypeMapping( recommendedDdlTypeCode ); } else { if ( Serializable.class.isAssignableFrom( domainJavaType.getJavaTypeClass() ) ) { jdbcTypeCode = Types.BLOB; } else { throw new IllegalArgumentException( String.format( Locale.ROOT, "JDBC type-code [%s (%s)] not known to have a corresponding LOB equivalent, and Java type is not Serializable (to use BLOB)", recommendedDdlTypeCode, JdbcTypeNameMapper.getTypeName( recommendedDdlTypeCode ) ) ); } } } else { jdbcTypeCode = recommendedDdlTypeCode; } return isNationalized() ? toNationalizedTypeCode( jdbcTypeCode ) : jdbcTypeCode; } public boolean isTypeSpecified() { return typeName != null; } public void setTypeParameters(Properties parameterMap) { this.typeParameters = parameterMap; } public void setTypeParameters(Map<String, ?> parameters) { if ( parameters != null ) { final var properties = new Properties(); properties.putAll( parameters ); setTypeParameters( properties ); } } public Properties getTypeParameters() { return typeParameters; } public void copyTypeFrom( SimpleValue sourceValue ) { setTypeName( sourceValue.getTypeName() ); setTypeParameters( sourceValue.getTypeParameters() ); type = sourceValue.type; attributeConverterDescriptor = sourceValue.attributeConverterDescriptor; } @Override public boolean isSame(Value other) { return this == other || other instanceof SimpleValue simpleValue && isSame( simpleValue ); } protected static boolean isSame(Value v1, Value v2) { return v1 == v2 || v1 != null && v2 != null && v1.isSame( v2 ); } public boolean isSame(SimpleValue other) { return Objects.equals( columns, other.columns ) && Objects.equals( typeName, other.typeName ) && Objects.equals( typeParameters, other.typeParameters ) && Objects.equals( table, other.table ) && Objects.equals( foreignKeyName, other.foreignKeyName ) && Objects.equals( foreignKeyDefinition, other.foreignKeyDefinition ); } @Override public String toString() { return getClass().getSimpleName() + '(' + columns + ')'; } public Object accept(ValueVisitor visitor) { return visitor.accept(this); } @Override public boolean[] getColumnInsertability() { return extractBooleansFromList( insertability ); } @Override public boolean hasAnyInsertableColumns() { //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < insertability.size(); i++ ) { if ( insertability.get( i ) ) { return true; } } return false; } @Override public boolean[] getColumnUpdateability() { return extractBooleansFromList( updatability ); } @Override public boolean hasAnyUpdatableColumns() { for ( int i = 0; i < updatability.size(); i++ ) { if ( updatability.get( i ) ) { return true; } } return false; } @Override public boolean isColumnInsertable(int index) { return !insertability.isEmpty() && insertability.get( index ); } @Override public boolean isColumnUpdateable(int index) { return !updatability.isEmpty() && updatability.get( index ); } public boolean isPartitionKey() { return partitionKey; } public void setPartitionKey(boolean partitionColumn) { this.partitionKey = partitionColumn; } private static boolean[] extractBooleansFromList(List<Boolean> list) { final boolean[] array = new boolean[ list.size() ]; int i = 0; for ( Boolean value : list ) { array[ i++ ] = value; } return array; } public ConverterDescriptor<?,?> getJpaAttributeConverterDescriptor() { return attributeConverterDescriptor; } public void setJpaAttributeConverterDescriptor(ConverterDescriptor<?,?> descriptor) { this.attributeConverterDescriptor = descriptor; } private static final Annotation[] NO_ANNOTATIONS = new Annotation[0]; private static Annotation[] getAnnotations(MemberDetails memberDetails) { final var directAnnotationUsages = memberDetails == null ? null : memberDetails.getDirectAnnotationUsages(); return directAnnotationUsages == null ? NO_ANNOTATIONS : directAnnotationUsages.toArray( Annotation[]::new ); } protected ParameterType createParameterType() { try { final String[] columnNames = new String[ columns.size() ]; final Long[] columnLengths = new Long[ columns.size() ]; for ( int i = 0; i < columns.size(); i++ ) { final var selectable = columns.get(i); if ( selectable instanceof Column column ) { columnNames[i] = column.getName(); columnLengths[i] = column.getLength(); } } // todo : not sure this works for handling @MapKeyEnumerated return createParameterType( columnNames, columnLengths ); } catch ( ClassLoadingException e ) { throw new MappingException( "Could not create DynamicParameterizedType for type: " + typeName, e ); } } private ParameterType createParameterType(String[] columnNames, Long[] columnLengths) { final var attribute = (MemberDetails) typeParameters.get( DynamicParameterizedType.XPROPERTY ); return new ParameterTypeImpl( classLoaderService() .classForTypeName( typeParameters.getProperty( DynamicParameterizedType.RETURNED_CLASS ) ), attribute != null ? attribute.getType() : null, getAnnotations( attribute ), table.getCatalog(), table.getSchema(), table.getName(), parseBoolean( typeParameters.getProperty( DynamicParameterizedType.IS_PRIMARY_KEY ) ), columnNames, columnLengths ); } private static final class ParameterTypeImpl implements ParameterType { private final Class<?> returnedClass; private final java.lang.reflect.Type returnedJavaType; private final Annotation[] annotationsMethod; private final String catalog; private final String schema; private final String table; private final boolean primaryKey; private final String[] columns; private final Long[] columnLengths; private ParameterTypeImpl( Class<?> returnedClass, TypeDetails returnedTypeDetails, Annotation[] annotationsMethod, String catalog, String schema, String table, boolean primaryKey, String[] columns, Long[] columnLengths) { this.returnedClass = returnedClass; this.annotationsMethod = annotationsMethod; this.catalog = catalog; this.schema = schema; this.table = table; this.primaryKey = primaryKey; this.columns = columns; this.columnLengths = columnLengths; if ( returnedTypeDetails == null ) { returnedJavaType = null; } else { returnedJavaType = returnedTypeDetails.getTypeKind() == PARAMETERIZED_TYPE ? ParameterizedTypeImpl.from( returnedTypeDetails.asParameterizedType() ) : returnedTypeDetails.determineRawClass().toJavaClass(); } } @Override public Class<?> getReturnedClass() { return returnedClass; } @Override public java.lang.reflect.Type getReturnedJavaType() { return returnedJavaType; } @Override public Annotation[] getAnnotationsMethod() { return annotationsMethod; } @Override public String getCatalog() { return catalog; } @Override public String getSchema() { return schema; } @Override public String getTable() { return table; } @Override public boolean isPrimaryKey() { return primaryKey; } @Override public String[] getColumns() { return columns; } @Override public Long[] getColumnLengths() { return columnLengths; } } private class IdGeneratorCreationContext implements GeneratorCreationContext { private final SimpleValue identifier; private final RootClass rootClass; private final Property property; private final GeneratorSettings defaults; public IdGeneratorCreationContext(SimpleValue identifier, RootClass rootClass, Property property, GeneratorSettings defaults) { this.identifier = identifier; this.rootClass = rootClass; this.property = property; this.defaults = defaults; } @Override public Database getDatabase() { return buildingContext.getMetadataCollector().getDatabase(); } @Override public ServiceRegistry getServiceRegistry() { return buildingContext.getBootstrapContext().getServiceRegistry(); } @Override public SqlStringGenerationContext getSqlStringGenerationContext() { return defaults.getSqlStringGenerationContext(); } @Override public String getDefaultCatalog() { return defaults.getDefaultCatalog(); } @Override public String getDefaultSchema() { return defaults.getDefaultSchema(); } @Override public RootClass getRootClass() { return rootClass; } @Override public PersistentClass getPersistentClass() { return rootClass; } @Override public Property getProperty() { return property; } @Override public Value getValue() { return identifier; } @Override public Type getType() { return SimpleValue.this.getType(); } // we could add this if it helps integrate old infrastructure // @Override // public Properties getParameters() { // final Value value = getProperty().getValue(); // if ( !value.isSimpleValue() ) { // throw new IllegalStateException( "not a simple-valued property" ); // } // final Dialect dialect = getDatabase().getDialect(); // return collectParameters( (SimpleValue) value, dialect, defaultCatalog, defaultSchema, rootClass ); // } // } }
googleapis/google-cloud-java
36,435
java-parametermanager/proto-google-cloud-parametermanager-v1/src/main/java/com/google/cloud/parametermanager/v1/RenderParameterVersionResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/parametermanager/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.parametermanager.v1; /** * * * <pre> * Message describing RenderParameterVersionResponse resource * </pre> * * Protobuf type {@code google.cloud.parametermanager.v1.RenderParameterVersionResponse} */ public final class RenderParameterVersionResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.parametermanager.v1.RenderParameterVersionResponse) RenderParameterVersionResponseOrBuilder { private static final long serialVersionUID = 0L; // Use RenderParameterVersionResponse.newBuilder() to construct. private RenderParameterVersionResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private RenderParameterVersionResponse() { parameterVersion_ = ""; renderedPayload_ = com.google.protobuf.ByteString.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new RenderParameterVersionResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.parametermanager.v1.V1mainProto .internal_static_google_cloud_parametermanager_v1_RenderParameterVersionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.parametermanager.v1.V1mainProto .internal_static_google_cloud_parametermanager_v1_RenderParameterVersionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.parametermanager.v1.RenderParameterVersionResponse.class, com.google.cloud.parametermanager.v1.RenderParameterVersionResponse.Builder.class); } private int bitField0_; public static final int PARAMETER_VERSION_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parameterVersion_ = ""; /** * * * <pre> * Output only. Resource identifier of a ParameterVersion in the format * `projects/&#42;&#47;locations/&#42;&#47;parameters/&#42;&#47;versions/&#42;`. * </pre> * * <code> * string parameter_version = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The parameterVersion. */ @java.lang.Override public java.lang.String getParameterVersion() { java.lang.Object ref = parameterVersion_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parameterVersion_ = s; return s; } } /** * * * <pre> * Output only. Resource identifier of a ParameterVersion in the format * `projects/&#42;&#47;locations/&#42;&#47;parameters/&#42;&#47;versions/&#42;`. * </pre> * * <code> * string parameter_version = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parameterVersion. */ @java.lang.Override public com.google.protobuf.ByteString getParameterVersionBytes() { java.lang.Object ref = parameterVersion_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parameterVersion_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAYLOAD_FIELD_NUMBER = 2; private com.google.cloud.parametermanager.v1.ParameterVersionPayload payload_; /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> * * @return Whether the payload field is set. */ @java.lang.Override public boolean hasPayload() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> * * @return The payload. */ @java.lang.Override public com.google.cloud.parametermanager.v1.ParameterVersionPayload getPayload() { return payload_ == null ? com.google.cloud.parametermanager.v1.ParameterVersionPayload.getDefaultInstance() : payload_; } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ @java.lang.Override public com.google.cloud.parametermanager.v1.ParameterVersionPayloadOrBuilder getPayloadOrBuilder() { return payload_ == null ? com.google.cloud.parametermanager.v1.ParameterVersionPayload.getDefaultInstance() : payload_; } public static final int RENDERED_PAYLOAD_FIELD_NUMBER = 3; private com.google.protobuf.ByteString renderedPayload_ = com.google.protobuf.ByteString.EMPTY; /** * * * <pre> * Output only. Server generated rendered version of the user provided payload * data (ParameterVersionPayload) which has substitutions of all (if any) * references to a SecretManager SecretVersion resources. This substitution * only works for a Parameter which is in JSON or YAML format. * </pre> * * <code>bytes rendered_payload = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The renderedPayload. */ @java.lang.Override public com.google.protobuf.ByteString getRenderedPayload() { return renderedPayload_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parameterVersion_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parameterVersion_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getPayload()); } if (!renderedPayload_.isEmpty()) { output.writeBytes(3, renderedPayload_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parameterVersion_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parameterVersion_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getPayload()); } if (!renderedPayload_.isEmpty()) { size += com.google.protobuf.CodedOutputStream.computeBytesSize(3, renderedPayload_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.parametermanager.v1.RenderParameterVersionResponse)) { return super.equals(obj); } com.google.cloud.parametermanager.v1.RenderParameterVersionResponse other = (com.google.cloud.parametermanager.v1.RenderParameterVersionResponse) obj; if (!getParameterVersion().equals(other.getParameterVersion())) return false; if (hasPayload() != other.hasPayload()) return false; if (hasPayload()) { if (!getPayload().equals(other.getPayload())) return false; } if (!getRenderedPayload().equals(other.getRenderedPayload())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARAMETER_VERSION_FIELD_NUMBER; hash = (53 * hash) + getParameterVersion().hashCode(); if (hasPayload()) { hash = (37 * hash) + PAYLOAD_FIELD_NUMBER; hash = (53 * hash) + getPayload().hashCode(); } hash = (37 * hash) + RENDERED_PAYLOAD_FIELD_NUMBER; hash = (53 * hash) + getRenderedPayload().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.parametermanager.v1.RenderParameterVersionResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message describing RenderParameterVersionResponse resource * </pre> * * Protobuf type {@code google.cloud.parametermanager.v1.RenderParameterVersionResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.parametermanager.v1.RenderParameterVersionResponse) com.google.cloud.parametermanager.v1.RenderParameterVersionResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.parametermanager.v1.V1mainProto .internal_static_google_cloud_parametermanager_v1_RenderParameterVersionResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.parametermanager.v1.V1mainProto .internal_static_google_cloud_parametermanager_v1_RenderParameterVersionResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.parametermanager.v1.RenderParameterVersionResponse.class, com.google.cloud.parametermanager.v1.RenderParameterVersionResponse.Builder.class); } // Construct using // com.google.cloud.parametermanager.v1.RenderParameterVersionResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getPayloadFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parameterVersion_ = ""; payload_ = null; if (payloadBuilder_ != null) { payloadBuilder_.dispose(); payloadBuilder_ = null; } renderedPayload_ = com.google.protobuf.ByteString.EMPTY; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.parametermanager.v1.V1mainProto .internal_static_google_cloud_parametermanager_v1_RenderParameterVersionResponse_descriptor; } @java.lang.Override public com.google.cloud.parametermanager.v1.RenderParameterVersionResponse getDefaultInstanceForType() { return com.google.cloud.parametermanager.v1.RenderParameterVersionResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.parametermanager.v1.RenderParameterVersionResponse build() { com.google.cloud.parametermanager.v1.RenderParameterVersionResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.parametermanager.v1.RenderParameterVersionResponse buildPartial() { com.google.cloud.parametermanager.v1.RenderParameterVersionResponse result = new com.google.cloud.parametermanager.v1.RenderParameterVersionResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.parametermanager.v1.RenderParameterVersionResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parameterVersion_ = parameterVersion_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.payload_ = payloadBuilder_ == null ? payload_ : payloadBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.renderedPayload_ = renderedPayload_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.parametermanager.v1.RenderParameterVersionResponse) { return mergeFrom( (com.google.cloud.parametermanager.v1.RenderParameterVersionResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.parametermanager.v1.RenderParameterVersionResponse other) { if (other == com.google.cloud.parametermanager.v1.RenderParameterVersionResponse .getDefaultInstance()) return this; if (!other.getParameterVersion().isEmpty()) { parameterVersion_ = other.parameterVersion_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasPayload()) { mergePayload(other.getPayload()); } if (other.getRenderedPayload() != com.google.protobuf.ByteString.EMPTY) { setRenderedPayload(other.getRenderedPayload()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parameterVersion_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getPayloadFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { renderedPayload_ = input.readBytes(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parameterVersion_ = ""; /** * * * <pre> * Output only. Resource identifier of a ParameterVersion in the format * `projects/&#42;&#47;locations/&#42;&#47;parameters/&#42;&#47;versions/&#42;`. * </pre> * * <code> * string parameter_version = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The parameterVersion. */ public java.lang.String getParameterVersion() { java.lang.Object ref = parameterVersion_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parameterVersion_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Output only. Resource identifier of a ParameterVersion in the format * `projects/&#42;&#47;locations/&#42;&#47;parameters/&#42;&#47;versions/&#42;`. * </pre> * * <code> * string parameter_version = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parameterVersion. */ public com.google.protobuf.ByteString getParameterVersionBytes() { java.lang.Object ref = parameterVersion_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parameterVersion_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Output only. Resource identifier of a ParameterVersion in the format * `projects/&#42;&#47;locations/&#42;&#47;parameters/&#42;&#47;versions/&#42;`. * </pre> * * <code> * string parameter_version = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @param value The parameterVersion to set. * @return This builder for chaining. */ public Builder setParameterVersion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parameterVersion_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Output only. Resource identifier of a ParameterVersion in the format * `projects/&#42;&#47;locations/&#42;&#47;parameters/&#42;&#47;versions/&#42;`. * </pre> * * <code> * string parameter_version = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParameterVersion() { parameterVersion_ = getDefaultInstance().getParameterVersion(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Output only. Resource identifier of a ParameterVersion in the format * `projects/&#42;&#47;locations/&#42;&#47;parameters/&#42;&#47;versions/&#42;`. * </pre> * * <code> * string parameter_version = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parameterVersion to set. * @return This builder for chaining. */ public Builder setParameterVersionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parameterVersion_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.parametermanager.v1.ParameterVersionPayload payload_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.parametermanager.v1.ParameterVersionPayload, com.google.cloud.parametermanager.v1.ParameterVersionPayload.Builder, com.google.cloud.parametermanager.v1.ParameterVersionPayloadOrBuilder> payloadBuilder_; /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> * * @return Whether the payload field is set. */ public boolean hasPayload() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> * * @return The payload. */ public com.google.cloud.parametermanager.v1.ParameterVersionPayload getPayload() { if (payloadBuilder_ == null) { return payload_ == null ? com.google.cloud.parametermanager.v1.ParameterVersionPayload.getDefaultInstance() : payload_; } else { return payloadBuilder_.getMessage(); } } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ public Builder setPayload(com.google.cloud.parametermanager.v1.ParameterVersionPayload value) { if (payloadBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payload_ = value; } else { payloadBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ public Builder setPayload( com.google.cloud.parametermanager.v1.ParameterVersionPayload.Builder builderForValue) { if (payloadBuilder_ == null) { payload_ = builderForValue.build(); } else { payloadBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ public Builder mergePayload( com.google.cloud.parametermanager.v1.ParameterVersionPayload value) { if (payloadBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && payload_ != null && payload_ != com.google.cloud.parametermanager.v1.ParameterVersionPayload .getDefaultInstance()) { getPayloadBuilder().mergeFrom(value); } else { payload_ = value; } } else { payloadBuilder_.mergeFrom(value); } if (payload_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ public Builder clearPayload() { bitField0_ = (bitField0_ & ~0x00000002); payload_ = null; if (payloadBuilder_ != null) { payloadBuilder_.dispose(); payloadBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ public com.google.cloud.parametermanager.v1.ParameterVersionPayload.Builder getPayloadBuilder() { bitField0_ |= 0x00000002; onChanged(); return getPayloadFieldBuilder().getBuilder(); } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ public com.google.cloud.parametermanager.v1.ParameterVersionPayloadOrBuilder getPayloadOrBuilder() { if (payloadBuilder_ != null) { return payloadBuilder_.getMessageOrBuilder(); } else { return payload_ == null ? com.google.cloud.parametermanager.v1.ParameterVersionPayload.getDefaultInstance() : payload_; } } /** * * * <pre> * Payload content of a ParameterVersion resource. * </pre> * * <code>.google.cloud.parametermanager.v1.ParameterVersionPayload payload = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.parametermanager.v1.ParameterVersionPayload, com.google.cloud.parametermanager.v1.ParameterVersionPayload.Builder, com.google.cloud.parametermanager.v1.ParameterVersionPayloadOrBuilder> getPayloadFieldBuilder() { if (payloadBuilder_ == null) { payloadBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.parametermanager.v1.ParameterVersionPayload, com.google.cloud.parametermanager.v1.ParameterVersionPayload.Builder, com.google.cloud.parametermanager.v1.ParameterVersionPayloadOrBuilder>( getPayload(), getParentForChildren(), isClean()); payload_ = null; } return payloadBuilder_; } private com.google.protobuf.ByteString renderedPayload_ = com.google.protobuf.ByteString.EMPTY; /** * * * <pre> * Output only. Server generated rendered version of the user provided payload * data (ParameterVersionPayload) which has substitutions of all (if any) * references to a SecretManager SecretVersion resources. This substitution * only works for a Parameter which is in JSON or YAML format. * </pre> * * <code>bytes rendered_payload = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return The renderedPayload. */ @java.lang.Override public com.google.protobuf.ByteString getRenderedPayload() { return renderedPayload_; } /** * * * <pre> * Output only. Server generated rendered version of the user provided payload * data (ParameterVersionPayload) which has substitutions of all (if any) * references to a SecretManager SecretVersion resources. This substitution * only works for a Parameter which is in JSON or YAML format. * </pre> * * <code>bytes rendered_payload = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @param value The renderedPayload to set. * @return This builder for chaining. */ public Builder setRenderedPayload(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } renderedPayload_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Output only. Server generated rendered version of the user provided payload * data (ParameterVersionPayload) which has substitutions of all (if any) * references to a SecretManager SecretVersion resources. This substitution * only works for a Parameter which is in JSON or YAML format. * </pre> * * <code>bytes rendered_payload = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * * @return This builder for chaining. */ public Builder clearRenderedPayload() { bitField0_ = (bitField0_ & ~0x00000004); renderedPayload_ = getDefaultInstance().getRenderedPayload(); onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.parametermanager.v1.RenderParameterVersionResponse) } // @@protoc_insertion_point(class_scope:google.cloud.parametermanager.v1.RenderParameterVersionResponse) private static final com.google.cloud.parametermanager.v1.RenderParameterVersionResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.parametermanager.v1.RenderParameterVersionResponse(); } public static com.google.cloud.parametermanager.v1.RenderParameterVersionResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<RenderParameterVersionResponse> PARSER = new com.google.protobuf.AbstractParser<RenderParameterVersionResponse>() { @java.lang.Override public RenderParameterVersionResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<RenderParameterVersionResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<RenderParameterVersionResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.parametermanager.v1.RenderParameterVersionResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,436
java-discoveryengine/proto-google-cloud-discoveryengine-v1beta/src/main/java/com/google/cloud/discoveryengine/v1beta/ListEvaluationsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/discoveryengine/v1beta/evaluation_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1beta; /** * * * <pre> * Request message for * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1beta.ListEvaluationsRequest} */ public final class ListEvaluationsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1beta.ListEvaluationsRequest) ListEvaluationsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListEvaluationsRequest.newBuilder() to construct. private ListEvaluationsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListEvaluationsRequest() { parent_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListEvaluationsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1beta.EvaluationServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListEvaluationsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1beta.EvaluationServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListEvaluationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.class, com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent location resource name, such as * `projects/{project}/locations/{location}`. * * If the caller does not have permission to list * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s under this * location, regardless of whether or not this location exists, a * `PERMISSION_DENIED` error is returned. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent location resource name, such as * `projects/{project}/locations/{location}`. * * If the caller does not have permission to list * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s under this * location, regardless of whether or not this location exists, a * `PERMISSION_DENIED` error is returned. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Maximum number of * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s to return. If * unspecified, defaults to 100. The maximum allowed value is 1000. Values * above 1000 will be coerced to 1000. * * If this field is negative, an `INVALID_ARGUMENT` error is returned. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A page token * [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], * received from a previous * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * must match the call that provided the page token. Otherwise, an * `INVALID_ARGUMENT` error is returned. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A page token * [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], * received from a previous * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * must match the call that provided the page token. Otherwise, an * `INVALID_ARGUMENT` error is returned. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest other = (com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1beta.ListEvaluationsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1beta.ListEvaluationsRequest) com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1beta.EvaluationServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListEvaluationsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1beta.EvaluationServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListEvaluationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.class, com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.Builder.class); } // Construct using com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.discoveryengine.v1beta.EvaluationServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListEvaluationsRequest_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest build() { com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest buildPartial() { com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest result = new com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest) { return mergeFrom((com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest other) { if (other == com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent location resource name, such as * `projects/{project}/locations/{location}`. * * If the caller does not have permission to list * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s under this * location, regardless of whether or not this location exists, a * `PERMISSION_DENIED` error is returned. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent location resource name, such as * `projects/{project}/locations/{location}`. * * If the caller does not have permission to list * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s under this * location, regardless of whether or not this location exists, a * `PERMISSION_DENIED` error is returned. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent location resource name, such as * `projects/{project}/locations/{location}`. * * If the caller does not have permission to list * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s under this * location, regardless of whether or not this location exists, a * `PERMISSION_DENIED` error is returned. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent location resource name, such as * `projects/{project}/locations/{location}`. * * If the caller does not have permission to list * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s under this * location, regardless of whether or not this location exists, a * `PERMISSION_DENIED` error is returned. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent location resource name, such as * `projects/{project}/locations/{location}`. * * If the caller does not have permission to list * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s under this * location, regardless of whether or not this location exists, a * `PERMISSION_DENIED` error is returned. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Maximum number of * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s to return. If * unspecified, defaults to 100. The maximum allowed value is 1000. Values * above 1000 will be coerced to 1000. * * If this field is negative, an `INVALID_ARGUMENT` error is returned. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Maximum number of * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s to return. If * unspecified, defaults to 100. The maximum allowed value is 1000. Values * above 1000 will be coerced to 1000. * * If this field is negative, an `INVALID_ARGUMENT` error is returned. * </pre> * * <code>int32 page_size = 2;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Maximum number of * [Evaluation][google.cloud.discoveryengine.v1beta.Evaluation]s to return. If * unspecified, defaults to 100. The maximum allowed value is 1000. Values * above 1000 will be coerced to 1000. * * If this field is negative, an `INVALID_ARGUMENT` error is returned. * </pre> * * <code>int32 page_size = 2;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A page token * [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], * received from a previous * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * must match the call that provided the page token. Otherwise, an * `INVALID_ARGUMENT` error is returned. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A page token * [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], * received from a previous * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * must match the call that provided the page token. Otherwise, an * `INVALID_ARGUMENT` error is returned. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A page token * [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], * received from a previous * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * must match the call that provided the page token. Otherwise, an * `INVALID_ARGUMENT` error is returned. * </pre> * * <code>string page_token = 3;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A page token * [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], * received from a previous * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * must match the call that provided the page token. Otherwise, an * `INVALID_ARGUMENT` error is returned. * </pre> * * <code>string page_token = 3;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A page token * [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListEvaluationsResponse.next_page_token], * received from a previous * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * call. Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to * [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1beta.EvaluationService.ListEvaluations] * must match the call that provided the page token. Otherwise, an * `INVALID_ARGUMENT` error is returned. * </pre> * * <code>string page_token = 3;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1beta.ListEvaluationsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1beta.ListEvaluationsRequest) private static final com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest(); } public static com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListEvaluationsRequest> PARSER = new com.google.protobuf.AbstractParser<ListEvaluationsRequest>() { @java.lang.Override public ListEvaluationsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListEvaluationsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListEvaluationsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListEvaluationsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,359
java-maps-routeoptimization/proto-google-maps-routeoptimization-v1/src/main/java/com/google/maps/routeoptimization/v1/ShipmentTypeIncompatibility.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/maps/routeoptimization/v1/route_optimization_service.proto // Protobuf Java Version: 3.25.8 package com.google.maps.routeoptimization.v1; /** * * * <pre> * Specifies incompatibilties between shipments depending on their * shipment_type. The appearance of incompatible shipments on the same route is * restricted based on the incompatibility mode. * </pre> * * Protobuf type {@code google.maps.routeoptimization.v1.ShipmentTypeIncompatibility} */ public final class ShipmentTypeIncompatibility extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.maps.routeoptimization.v1.ShipmentTypeIncompatibility) ShipmentTypeIncompatibilityOrBuilder { private static final long serialVersionUID = 0L; // Use ShipmentTypeIncompatibility.newBuilder() to construct. private ShipmentTypeIncompatibility(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ShipmentTypeIncompatibility() { types_ = com.google.protobuf.LazyStringArrayList.emptyList(); incompatibilityMode_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ShipmentTypeIncompatibility(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto .internal_static_google_maps_routeoptimization_v1_ShipmentTypeIncompatibility_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto .internal_static_google_maps_routeoptimization_v1_ShipmentTypeIncompatibility_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.class, com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.Builder.class); } /** * * * <pre> * Modes defining how the appearance of incompatible shipments are restricted * on the same route. * </pre> * * Protobuf enum {@code * google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode} */ public enum IncompatibilityMode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unspecified incompatibility mode. This value should never be used. * </pre> * * <code>INCOMPATIBILITY_MODE_UNSPECIFIED = 0;</code> */ INCOMPATIBILITY_MODE_UNSPECIFIED(0), /** * * * <pre> * In this mode, two shipments with incompatible types can never share the * same vehicle. * </pre> * * <code>NOT_PERFORMED_BY_SAME_VEHICLE = 1;</code> */ NOT_PERFORMED_BY_SAME_VEHICLE(1), /** * * * <pre> * For two shipments with incompatible types with the * `NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY` incompatibility mode: * * * If both are pickups only (no deliveries) or deliveries only (no * pickups), they cannot share the same vehicle at all. * * If one of the shipments has a delivery and the other a pickup, the two * shipments can share the same vehicle iff the former shipment is * delivered before the latter is picked up. * </pre> * * <code>NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY = 2;</code> */ NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY(2), UNRECOGNIZED(-1), ; /** * * * <pre> * Unspecified incompatibility mode. This value should never be used. * </pre> * * <code>INCOMPATIBILITY_MODE_UNSPECIFIED = 0;</code> */ public static final int INCOMPATIBILITY_MODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * In this mode, two shipments with incompatible types can never share the * same vehicle. * </pre> * * <code>NOT_PERFORMED_BY_SAME_VEHICLE = 1;</code> */ public static final int NOT_PERFORMED_BY_SAME_VEHICLE_VALUE = 1; /** * * * <pre> * For two shipments with incompatible types with the * `NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY` incompatibility mode: * * * If both are pickups only (no deliveries) or deliveries only (no * pickups), they cannot share the same vehicle at all. * * If one of the shipments has a delivery and the other a pickup, the two * shipments can share the same vehicle iff the former shipment is * delivered before the latter is picked up. * </pre> * * <code>NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY = 2;</code> */ public static final int NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static IncompatibilityMode valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static IncompatibilityMode forNumber(int value) { switch (value) { case 0: return INCOMPATIBILITY_MODE_UNSPECIFIED; case 1: return NOT_PERFORMED_BY_SAME_VEHICLE; case 2: return NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<IncompatibilityMode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<IncompatibilityMode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<IncompatibilityMode>() { public IncompatibilityMode findValueByNumber(int number) { return IncompatibilityMode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.getDescriptor() .getEnumTypes() .get(0); } private static final IncompatibilityMode[] VALUES = values(); public static IncompatibilityMode valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private IncompatibilityMode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode) } public static final int TYPES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList types_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @return A list containing the types. */ public com.google.protobuf.ProtocolStringList getTypesList() { return types_; } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @return The count of types. */ public int getTypesCount() { return types_.size(); } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param index The index of the element to return. * @return The types at the given index. */ public java.lang.String getTypes(int index) { return types_.get(index); } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param index The index of the value to return. * @return The bytes of the types at the given index. */ public com.google.protobuf.ByteString getTypesBytes(int index) { return types_.getByteString(index); } public static final int INCOMPATIBILITY_MODE_FIELD_NUMBER = 2; private int incompatibilityMode_ = 0; /** * * * <pre> * Mode applied to the incompatibility. * </pre> * * <code> * .google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode incompatibility_mode = 2; * </code> * * @return The enum numeric value on the wire for incompatibilityMode. */ @java.lang.Override public int getIncompatibilityModeValue() { return incompatibilityMode_; } /** * * * <pre> * Mode applied to the incompatibility. * </pre> * * <code> * .google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode incompatibility_mode = 2; * </code> * * @return The incompatibilityMode. */ @java.lang.Override public com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode getIncompatibilityMode() { com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode result = com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode .forNumber(incompatibilityMode_); return result == null ? com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode .UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < types_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, types_.getRaw(i)); } if (incompatibilityMode_ != com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode .INCOMPATIBILITY_MODE_UNSPECIFIED .getNumber()) { output.writeEnum(2, incompatibilityMode_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; { int dataSize = 0; for (int i = 0; i < types_.size(); i++) { dataSize += computeStringSizeNoTag(types_.getRaw(i)); } size += dataSize; size += 1 * getTypesList().size(); } if (incompatibilityMode_ != com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode .INCOMPATIBILITY_MODE_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, incompatibilityMode_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility)) { return super.equals(obj); } com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility other = (com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility) obj; if (!getTypesList().equals(other.getTypesList())) return false; if (incompatibilityMode_ != other.incompatibilityMode_) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getTypesCount() > 0) { hash = (37 * hash) + TYPES_FIELD_NUMBER; hash = (53 * hash) + getTypesList().hashCode(); } hash = (37 * hash) + INCOMPATIBILITY_MODE_FIELD_NUMBER; hash = (53 * hash) + incompatibilityMode_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Specifies incompatibilties between shipments depending on their * shipment_type. The appearance of incompatible shipments on the same route is * restricted based on the incompatibility mode. * </pre> * * Protobuf type {@code google.maps.routeoptimization.v1.ShipmentTypeIncompatibility} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.maps.routeoptimization.v1.ShipmentTypeIncompatibility) com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibilityOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto .internal_static_google_maps_routeoptimization_v1_ShipmentTypeIncompatibility_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto .internal_static_google_maps_routeoptimization_v1_ShipmentTypeIncompatibility_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.class, com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.Builder.class); } // Construct using com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; types_ = com.google.protobuf.LazyStringArrayList.emptyList(); incompatibilityMode_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.maps.routeoptimization.v1.RouteOptimizationServiceProto .internal_static_google_maps_routeoptimization_v1_ShipmentTypeIncompatibility_descriptor; } @java.lang.Override public com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility getDefaultInstanceForType() { return com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.getDefaultInstance(); } @java.lang.Override public com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility build() { com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility buildPartial() { com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility result = new com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { types_.makeImmutable(); result.types_ = types_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.incompatibilityMode_ = incompatibilityMode_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility) { return mergeFrom((com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility other) { if (other == com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.getDefaultInstance()) return this; if (!other.types_.isEmpty()) { if (types_.isEmpty()) { types_ = other.types_; bitField0_ |= 0x00000001; } else { ensureTypesIsMutable(); types_.addAll(other.types_); } onChanged(); } if (other.incompatibilityMode_ != 0) { setIncompatibilityModeValue(other.getIncompatibilityModeValue()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); ensureTypesIsMutable(); types_.add(s); break; } // case 10 case 16: { incompatibilityMode_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.LazyStringArrayList types_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureTypesIsMutable() { if (!types_.isModifiable()) { types_ = new com.google.protobuf.LazyStringArrayList(types_); } bitField0_ |= 0x00000001; } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @return A list containing the types. */ public com.google.protobuf.ProtocolStringList getTypesList() { types_.makeImmutable(); return types_; } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @return The count of types. */ public int getTypesCount() { return types_.size(); } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param index The index of the element to return. * @return The types at the given index. */ public java.lang.String getTypes(int index) { return types_.get(index); } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param index The index of the value to return. * @return The bytes of the types at the given index. */ public com.google.protobuf.ByteString getTypesBytes(int index) { return types_.getByteString(index); } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param index The index to set the value at. * @param value The types to set. * @return This builder for chaining. */ public Builder setTypes(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTypesIsMutable(); types_.set(index, value); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param value The types to add. * @return This builder for chaining. */ public Builder addTypes(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTypesIsMutable(); types_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param values The types to add. * @return This builder for chaining. */ public Builder addAllTypes(java.lang.Iterable<java.lang.String> values) { ensureTypesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, types_); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @return This builder for chaining. */ public Builder clearTypes() { types_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); ; onChanged(); return this; } /** * * * <pre> * List of incompatible types. Two shipments having different `shipment_types` * among those listed are "incompatible". * </pre> * * <code>repeated string types = 1;</code> * * @param value The bytes of the types to add. * @return This builder for chaining. */ public Builder addTypesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureTypesIsMutable(); types_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } private int incompatibilityMode_ = 0; /** * * * <pre> * Mode applied to the incompatibility. * </pre> * * <code> * .google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode incompatibility_mode = 2; * </code> * * @return The enum numeric value on the wire for incompatibilityMode. */ @java.lang.Override public int getIncompatibilityModeValue() { return incompatibilityMode_; } /** * * * <pre> * Mode applied to the incompatibility. * </pre> * * <code> * .google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode incompatibility_mode = 2; * </code> * * @param value The enum numeric value on the wire for incompatibilityMode to set. * @return This builder for chaining. */ public Builder setIncompatibilityModeValue(int value) { incompatibilityMode_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Mode applied to the incompatibility. * </pre> * * <code> * .google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode incompatibility_mode = 2; * </code> * * @return The incompatibilityMode. */ @java.lang.Override public com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode getIncompatibilityMode() { com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode result = com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode .forNumber(incompatibilityMode_); return result == null ? com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode .UNRECOGNIZED : result; } /** * * * <pre> * Mode applied to the incompatibility. * </pre> * * <code> * .google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode incompatibility_mode = 2; * </code> * * @param value The incompatibilityMode to set. * @return This builder for chaining. */ public Builder setIncompatibilityMode( com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; incompatibilityMode_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Mode applied to the incompatibility. * </pre> * * <code> * .google.maps.routeoptimization.v1.ShipmentTypeIncompatibility.IncompatibilityMode incompatibility_mode = 2; * </code> * * @return This builder for chaining. */ public Builder clearIncompatibilityMode() { bitField0_ = (bitField0_ & ~0x00000002); incompatibilityMode_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.maps.routeoptimization.v1.ShipmentTypeIncompatibility) } // @@protoc_insertion_point(class_scope:google.maps.routeoptimization.v1.ShipmentTypeIncompatibility) private static final com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility(); } public static com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ShipmentTypeIncompatibility> PARSER = new com.google.protobuf.AbstractParser<ShipmentTypeIncompatibility>() { @java.lang.Override public ShipmentTypeIncompatibility parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ShipmentTypeIncompatibility> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ShipmentTypeIncompatibility> getParserForType() { return PARSER; } @java.lang.Override public com.google.maps.routeoptimization.v1.ShipmentTypeIncompatibility getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/incubator-hugegraph
36,169
hugegraph-server/hugegraph-test/src/main/java/org/apache/hugegraph/core/RamTableTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hugegraph.core; import java.io.File; import java.nio.file.Paths; import java.util.Iterator; import java.util.Objects; import org.apache.commons.io.FileUtils; import org.apache.hugegraph.HugeGraph; import org.apache.hugegraph.backend.id.Id; import org.apache.hugegraph.backend.id.IdGenerator; import org.apache.hugegraph.backend.query.Query; import org.apache.hugegraph.backend.store.ram.RamTable; import org.apache.hugegraph.backend.tx.GraphTransaction; import org.apache.hugegraph.schema.SchemaManager; import org.apache.hugegraph.structure.HugeEdge; import org.apache.hugegraph.structure.HugeVertex; import org.apache.hugegraph.testutil.Assert; import org.apache.hugegraph.testutil.Whitebox; import org.apache.hugegraph.type.define.Directions; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; public class RamTableTest extends BaseCoreTest { private Object ramtable; @Override @Before public void setup() { super.setup(); HugeGraph graph = this.graph(); Assume.assumeTrue("Ramtable is not supported by backend", graph.backendStoreFeatures().supportsScanKeyPrefix()); this.ramtable = Whitebox.getInternalState(graph, "ramtable"); if (this.ramtable == null) { Whitebox.setInternalState(graph, "ramtable", new RamTable(graph, 2000, 1200)); } graph.schema().vertexLabel("vl1").useCustomizeNumberId().create(); graph.schema().vertexLabel("vl2").useCustomizeNumberId().create(); graph.schema().edgeLabel("el1") .sourceLabel("vl1") .targetLabel("vl1") .create(); graph.schema().edgeLabel("el2") .sourceLabel("vl2") .targetLabel("vl2") .create(); } @Override @After public void teardown() throws Exception { super.teardown(); File export = Paths.get(RamTable.EXPORT_PATH).toFile(); if (export.exists()) { FileUtils.forceDelete(export); } HugeGraph graph = this.graph(); Whitebox.setInternalState(graph, "ramtable", this.ramtable); } @Test public void testReloadAndQuery() throws Exception { // FIXME: skip this test for hstore Assume.assumeTrue("skip this test for hstore", Objects.equals("hstore", System.getProperty("backend"))); HugeGraph graph = this.graph(); // insert vertices and edges for (int i = 0; i < 100; i++) { Vertex v1 = graph.addVertex(T.label, "vl1", T.id, i); Vertex v2 = graph.addVertex(T.label, "vl1", T.id, i + 100); v1.addEdge("el1", v2); } graph.tx().commit(); for (int i = 1000; i < 1100; i++) { Vertex v1 = graph.addVertex(T.label, "vl2", T.id, i); Vertex v2 = graph.addVertex(T.label, "vl2", T.id, i + 100); v1.addEdge("el2", v2); } graph.tx().commit(); // reload ramtable Whitebox.invoke(graph.getClass(), "reloadRamtable", graph); // query edges for (int i = 0; i < 100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertFalse(edges.hasNext()); } for (int i = 1000; i < 1100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertFalse(edges.hasNext()); } } @Test public void testReloadFromFileAndQuery() throws Exception { // FIXME: skip this test for hstore Assume.assumeTrue("skip this test for hstore", Objects.equals("hstore", System.getProperty("backend"))); HugeGraph graph = this.graph(); // insert vertices and edges for (int i = 0; i < 100; i++) { Vertex v1 = graph.addVertex(T.label, "vl1", T.id, i); Vertex v2 = graph.addVertex(T.label, "vl1", T.id, i + 100); v1.addEdge("el1", v2); } graph.tx().commit(); for (int i = 1000; i < 1100; i++) { Vertex v1 = graph.addVertex(T.label, "vl2", T.id, i); Vertex v2 = graph.addVertex(T.label, "vl2", T.id, i + 100); v1.addEdge("el2", v2); } graph.tx().commit(); // reload ramtable Whitebox.invoke(graph.getClass(), "reloadRamtable", graph); // query edges for (int i = 0; i < 100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertFalse(edges.hasNext()); } for (int i = 1000; i < 1100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertFalse(edges.hasNext()); } // reload ramtable from file Whitebox.invoke(graph.getClass(), "reloadRamtable", graph, true); // query edges again for (int i = 0; i < 100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertFalse(edges.hasNext()); } for (int i = 1000; i < 1100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertFalse(edges.hasNext()); } } @Test public void testReloadAndQueryWithMultiEdges() throws Exception { // FIXME: skip this test for hstore Assume.assumeTrue("skip this test for hstore", Objects.equals("hstore", System.getProperty("backend"))); HugeGraph graph = this.graph(); // insert vertices and edges for (int i = 0; i < 100; i++) { Vertex v1 = graph.addVertex(T.label, "vl1", T.id, i); Vertex v2 = graph.addVertex(T.label, "vl1", T.id, i + 100); Vertex v3 = graph.addVertex(T.label, "vl1", T.id, i + 200); v1.addEdge("el1", v2); v1.addEdge("el1", v3); v3.addEdge("el1", v1); } graph.tx().commit(); for (int i = 1000; i < 1100; i++) { Vertex v1 = graph.addVertex(T.label, "vl2", T.id, i); Vertex v2 = graph.addVertex(T.label, "vl2", T.id, i + 100); Vertex v3 = graph.addVertex(T.label, "vl2", T.id, i + 200); v1.addEdge("el2", v2); v1.addEdge("el2", v3); v2.addEdge("el2", v3); } graph.tx().commit(); // reload ramtable Whitebox.invoke(graph.getClass(), "reloadRamtable", graph); // query edges by OUT for (int i = 0; i < 100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 200, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertFalse(edges.hasNext()); } // query edges by BOTH for (int i = 0; i < 100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.BOTH, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 200, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 200, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.IN, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertFalse(edges.hasNext()); } // query edges by IN for (int i = 0; i < 100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.IN, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 200, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.IN, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertFalse(edges.hasNext()); } // query edges by OUT for (int i = 1000; i < 1100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 200, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertFalse(edges.hasNext()); } // query edges by BOTH for (int i = 1000; i < 1100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.BOTH, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(i + 200, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertFalse(edges.hasNext()); } // query edges by IN for (int i = 1000; i < 1100; i++) { Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(i), Directions.IN, null); Assert.assertFalse(edges.hasNext()); } } @Test public void testReloadAndQueryWithBigVertex() throws Exception { // FIXME: skip this test for hstore Assume.assumeTrue("skip this test for hstore", Objects.equals("hstore", System.getProperty("backend"))); HugeGraph graph = this.graph(); // only enable this test when ram > 20G boolean enableBigRamTest = false; long big1 = 2400000000L; long big2 = 4200000000L; if (!enableBigRamTest) { big1 = 100L; big2 = 1000L; } // insert vertices and edges for (int i = 0; i < 100; i++) { Vertex v1 = graph.addVertex(T.label, "vl1", T.id, i + big1); Vertex v2 = graph.addVertex(T.label, "vl1", T.id, i + big1 + 100); v1.addEdge("el1", v2); } graph.tx().commit(); for (int i = 0; i < 100; i++) { Vertex v1 = graph.addVertex(T.label, "vl2", T.id, i + big2); Vertex v2 = graph.addVertex(T.label, "vl2", T.id, i + big2); v1.addEdge("el2", v2); } graph.tx().commit(); // reload ramtable Whitebox.invoke(graph.getClass(), "reloadRamtable", graph); // query edges for (int i = 0; i < 100; i++) { long source = i + big1; Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(source), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(source, edge.id().ownerVertexId().asLong()); Assert.assertEquals(i + big1 + 100, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el1", edge.label()); Assert.assertFalse(edges.hasNext()); } for (int i = 0; i < 100; i++) { long source = i + big2; Iterator<Edge> edges = this.edgesOfVertex(IdGenerator.of(source), Directions.OUT, null); Assert.assertTrue(edges.hasNext()); HugeEdge edge = (HugeEdge) edges.next(); Assert.assertEquals(source, edge.id().ownerVertexId().asLong()); Assert.assertEquals(i + big2, edge.id().otherVertexId().asLong()); Assert.assertEquals(Directions.OUT, edge.direction()); Assert.assertEquals("el2", edge.label()); Assert.assertFalse(edges.hasNext()); } } @Test public void testReloadAndQueryWithProperty() throws Exception { // FIXME: skip this test for hstore Assume.assumeTrue("skip this test for hstore", Objects.equals("hstore", System.getProperty("backend"))); HugeGraph graph = this.graph(); SchemaManager schema = graph.schema(); schema.propertyKey("name") .asText() .create(); schema.vertexLabel("person") .properties("name") .useCustomizeNumberId() .create(); schema.edgeLabel("next") .sourceLabel("person") .targetLabel("person") .properties("name") .create(); GraphTraversalSource g = graph.traversal(); g.addV("person").property(T.id, 1).property("name", "A").as("a") .addV("person").property(T.id, 2).property("name", "B").as("b") .addV("person").property(T.id, 3).property("name", "C").as("c") .addV("person").property(T.id, 4).property("name", "D").as("d") .addV("person").property(T.id, 5).property("name", "E").as("e") .addV("person").property(T.id, 6).property("name", "F").as("f") .addE("next").from("a").to("b").property("name", "ab") .addE("next").from("b").to("c").property("name", "bc") .addE("next").from("b").to("d").property("name", "bd") .addE("next").from("c").to("d").property("name", "cd") .addE("next").from("c").to("e").property("name", "ce") .addE("next").from("d").to("e").property("name", "de") .addE("next").from("e").to("f").property("name", "ef") .addE("next").from("f").to("d").property("name", "fd") .iterate(); graph.tx().commit(); Object ramtable = Whitebox.getInternalState(graph, "ramtable"); Assert.assertNotNull("The ramtable is not enabled", ramtable); // reload ramtable Whitebox.invoke(graph.getClass(), "reloadRamtable", graph); GraphTraversal<Vertex, Vertex> vertices; HugeVertex vertex; GraphTraversal<Vertex, Edge> edges; HugeEdge edge; // A vertices = g.V(1).out(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertFalse(vertex.isPropLoaded()); Assert.assertEquals(2L, vertex.id().asObject()); Assert.assertEquals("B", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(1).outE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertFalse(edge.isPropLoaded()); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("ab", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(1).in(); Assert.assertFalse(vertices.hasNext()); edges = g.V(1).inE(); Assert.assertFalse(edges.hasNext()); vertices = g.V(1).both(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(2L, vertex.id().asObject()); Assert.assertEquals("B", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(1).bothE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("ab", edge.value("name")); Assert.assertFalse(edges.hasNext()); // B vertices = g.V(2).out(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(3L, vertex.id().asObject()); Assert.assertEquals("C", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(2).outE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("bc", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("bd", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(2).in(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(1L, vertex.id().asObject()); Assert.assertEquals("A", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(2).inE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("ab", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(2).both(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(3L, vertex.id().asObject()); Assert.assertEquals("C", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(1L, vertex.id().asObject()); Assert.assertEquals("A", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(2).bothE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("bc", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("bd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("ab", edge.value("name")); Assert.assertFalse(edges.hasNext()); // C vertices = g.V(3).out(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(5L, vertex.id().asObject()); Assert.assertEquals("E", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(3).outE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("cd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("ce", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(3).in(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(2L, vertex.id().asObject()); Assert.assertEquals("B", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(3).inE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("bc", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(3).both(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(5L, vertex.id().asObject()); Assert.assertEquals("E", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(2L, vertex.id().asObject()); Assert.assertEquals("B", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(3).bothE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("cd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("ce", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("bc", edge.value("name")); Assert.assertFalse(edges.hasNext()); // D vertices = g.V(4).out(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(5L, vertex.id().asObject()); Assert.assertEquals("E", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(4).outE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("de", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(4).in(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(2L, vertex.id().asObject()); Assert.assertEquals("B", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(3L, vertex.id().asObject()); Assert.assertEquals("C", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(6L, vertex.id().asObject()); Assert.assertEquals("F", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(4).inE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("bd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("cd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("fd", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(4).both(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(5L, vertex.id().asObject()); Assert.assertEquals("E", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(2L, vertex.id().asObject()); Assert.assertEquals("B", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(3L, vertex.id().asObject()); Assert.assertEquals("C", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(6L, vertex.id().asObject()); Assert.assertEquals("F", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(4).bothE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("de", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("bd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("cd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("fd", edge.value("name")); Assert.assertFalse(edges.hasNext()); // E vertices = g.V(5).out(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(6L, vertex.id().asObject()); Assert.assertEquals("F", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(5).outE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("ef", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(5).in(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(3L, vertex.id().asObject()); Assert.assertEquals("C", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(5).inE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("ce", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("de", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(5).both(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(6L, vertex.id().asObject()); Assert.assertEquals("F", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(3L, vertex.id().asObject()); Assert.assertEquals("C", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(5).bothE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("ef", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("ce", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("de", edge.value("name")); Assert.assertFalse(edges.hasNext()); // F vertices = g.V(6).out(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(6).outE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("fd", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(6).in(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(5L, vertex.id().asObject()); Assert.assertEquals("E", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(6).inE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("ef", edge.value("name")); Assert.assertFalse(edges.hasNext()); vertices = g.V(6).both(); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(4L, vertex.id().asObject()); Assert.assertEquals("D", vertex.value("name")); Assert.assertTrue(vertices.hasNext()); vertex = (HugeVertex) vertices.next(); Assert.assertEquals(5L, vertex.id().asObject()); Assert.assertEquals("E", vertex.value("name")); Assert.assertFalse(vertices.hasNext()); edges = g.V(6).bothE(); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.OUT, edge.id().direction()); Assert.assertEquals("fd", edge.value("name")); Assert.assertTrue(edges.hasNext()); edge = (HugeEdge) edges.next(); Assert.assertEquals(Directions.IN, edge.id().direction()); Assert.assertEquals("ef", edge.value("name")); Assert.assertFalse(edges.hasNext()); } private Iterator<Edge> edgesOfVertex(Id source, Directions dir, Id label) { Id[] labels = {}; if (label != null) { labels = new Id[]{label}; } Query query = GraphTransaction.constructEdgesQuery(source, dir, labels); return this.graph().edges(query); } }
google/j2objc
36,666
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/PluralFormat.java
/* GENERATED SOURCE. DO NOT MODIFY. */ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* ******************************************************************************* * Copyright (C) 2007-2016, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* */ package android.icu.text; import java.io.IOException; import java.io.ObjectInputStream; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.Locale; import java.util.Map; import android.icu.impl.Utility; import android.icu.text.PluralRules.FixedDecimal; import android.icu.text.PluralRules.PluralType; import android.icu.util.ULocale; import android.icu.util.ULocale.Category; /** * <code>PluralFormat</code> supports the creation of internationalized * messages with plural inflection. It is based on <i>plural * selection</i>, i.e. the caller specifies messages for each * plural case that can appear in the user's language and the * <code>PluralFormat</code> selects the appropriate message based on * the number. * * <h3>The Problem of Plural Forms in Internationalized Messages</h3> * <p> * Different languages have different ways to inflect * plurals. Creating internationalized messages that include plural * forms is only feasible when the framework is able to handle plural * forms of <i>all</i> languages correctly. <code>ChoiceFormat</code> * doesn't handle this well, because it attaches a number interval to * each message and selects the message whose interval contains a * given number. This can only handle a finite number of * intervals. But in some languages, like Polish, one plural case * applies to infinitely many intervals (e.g., the paucal case applies to * numbers ending with 2, 3, or 4 except those ending with 12, 13, or * 14). Thus <code>ChoiceFormat</code> is not adequate. * <p> * <code>PluralFormat</code> deals with this by breaking the problem * into two parts: * <ul> * <li>It uses <code>PluralRules</code> that can define more complex * conditions for a plural case than just a single interval. These plural * rules define both what plural cases exist in a language, and to * which numbers these cases apply. * <li>It provides predefined plural rules for many languages. Thus, the programmer * need not worry about the plural cases of a language and * does not have to define the plural cases; they can simply * use the predefined keywords. The whole plural formatting of messages can * be done using localized patterns from resource bundles. For predefined plural * rules, see the CLDR <i>Language Plural Rules</i> page at * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * </ul> * * <h4>Usage of <code>PluralFormat</code></h4> * <p>Note: Typically, plural formatting is done via <code>MessageFormat</code> * with a <code>plural</code> argument type, * rather than using a stand-alone <code>PluralFormat</code>. * <p> * This discussion assumes that you use <code>PluralFormat</code> with * a predefined set of plural rules. You can create one using one of * the constructors that takes a <code>ULocale</code> object. To * specify the message pattern, you can either pass it to the * constructor or set it explicitly using the * <code>applyPattern()</code> method. The <code>format()</code> * method takes a number object and selects the message of the * matching plural case. This message will be returned. * * <h5>Patterns and Their Interpretation</h5> * <p> * The pattern text defines the message output for each plural case of the * specified locale. Syntax: * <blockquote><pre> * pluralStyle = [offsetValue] (selector '{' message '}')+ * offsetValue = "offset:" number * selector = explicitValue | keyword * explicitValue = '=' number // adjacent, no white space in between * keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+ * message: see {@link MessageFormat} * </pre></blockquote> * Pattern_White_Space between syntax elements is ignored, except * between the {curly braces} and their sub-message, * and between the '=' and the number of an explicitValue. * <p> * There are 6 predefined case keywords in CLDR/ICU - 'zero', 'one', 'two', 'few', 'many' and * 'other'. You always have to define a message text for the default plural case * "<code>other</code>" which is contained in every rule set. * If you do not specify a message text for a particular plural case, the * message text of the plural case "<code>other</code>" gets assigned to this * plural case. * <p> * When formatting, the input number is first matched against the explicitValue clauses. * If there is no exact-number match, then a keyword is selected by calling * the <code>PluralRules</code> with the input number <em>minus the offset</em>. * (The offset defaults to 0 if it is omitted from the pattern string.) * If there is no clause with that keyword, then the "other" clauses is returned. * <p> * An unquoted pound sign (<code>#</code>) in the selected sub-message * itself (i.e., outside of arguments nested in the sub-message) * is replaced by the input number minus the offset. * The number-minus-offset value is formatted using a * <code>NumberFormat</code> for the <code>PluralFormat</code>'s locale. If you * need special number formatting, you have to use a <code>MessageFormat</code> * and explicitly specify a <code>NumberFormat</code> argument. * <strong>Note:</strong> That argument is formatting without subtracting the offset! * If you need a custom format and have a non-zero offset, then you need to pass the * number-minus-offset value as a separate parameter. * * <p>For a usage example, see the {@link MessageFormat} class documentation. * * <h4>Defining Custom Plural Rules</h4> * <p>If you need to use <code>PluralFormat</code> with custom rules, you can * create a <code>PluralRules</code> object and pass it to * <code>PluralFormat</code>'s constructor. If you also specify a locale in this * constructor, this locale will be used to format the number in the message * texts. * <p> * For more information about <code>PluralRules</code>, see * {@link PluralRules}. * * @author tschumann (Tim Schumann) */ public class PluralFormat extends UFormat { private static final long serialVersionUID = 1L; /** * The locale used for standard number formatting and getting the predefined * plural rules (if they were not defined explicitely). * @serial */ private ULocale ulocale = null; /** * The plural rules used for plural selection. * @serial */ private PluralRules pluralRules = null; /** * The applied pattern string. * @serial */ private String pattern = null; /** * The MessagePattern which contains the parsed structure of the pattern string. */ transient private MessagePattern msgPattern; /** * Obsolete with use of MessagePattern since ICU 4.8. Used to be: * The format messages for each plural case. It is a mapping: * <code>String</code>(plural case keyword) --&gt; <code>String</code> * (message for this plural case). * @serial */ private Map<String, String> parsedValues = null; /** * This <code>NumberFormat</code> is used for the standard formatting of * the number inserted into the message. * @serial */ private NumberFormat numberFormat = null; /** * The offset to subtract before invoking plural rules. */ transient private double offset = 0; /** * Creates a new cardinal-number <code>PluralFormat</code> for the default <code>FORMAT</code> locale. * This locale will be used to get the set of plural rules and for standard * number formatting. * @see Category#FORMAT */ public PluralFormat() { init(null, PluralType.CARDINAL, ULocale.getDefault(Category.FORMAT), null); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given locale. * @param ulocale the <code>PluralFormat</code> will be configured with * rules for this locale. This locale will also be used for standard * number formatting. */ public PluralFormat(ULocale ulocale) { init(null, PluralType.CARDINAL, ulocale, null); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given * {@link java.util.Locale}. * @param locale the <code>PluralFormat</code> will be configured with * rules for this locale. This locale will also be used for standard * number formatting. */ public PluralFormat(Locale locale) { this(ULocale.forLocale(locale)); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given set of rules. * The standard number formatting will be done using the default <code>FORMAT</code> locale. * @param rules defines the behavior of the <code>PluralFormat</code> * object. * @see Category#FORMAT */ public PluralFormat(PluralRules rules) { init(rules, PluralType.CARDINAL, ULocale.getDefault(Category.FORMAT), null); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given set of rules. * The standard number formatting will be done using the given locale. * @param ulocale the default number formatting will be done using this * locale. * @param rules defines the behavior of the <code>PluralFormat</code> * object. */ public PluralFormat(ULocale ulocale, PluralRules rules) { init(rules, PluralType.CARDINAL, ulocale, null); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given set of rules. * The standard number formatting will be done using the given locale. * @param locale the default number formatting will be done using this * locale. * @param rules defines the behavior of the <code>PluralFormat</code> * object. */ public PluralFormat(Locale locale, PluralRules rules) { this(ULocale.forLocale(locale), rules); } /** * Creates a new <code>PluralFormat</code> for the plural type. * The standard number formatting will be done using the given locale. * @param ulocale the default number formatting will be done using this * locale. * @param type The plural type (e.g., cardinal or ordinal). */ public PluralFormat(ULocale ulocale, PluralType type) { init(null, type, ulocale, null); } /** * Creates a new <code>PluralFormat</code> for the plural type. * The standard number formatting will be done using the given {@link java.util.Locale}. * @param locale the default number formatting will be done using this * locale. * @param type The plural type (e.g., cardinal or ordinal). */ public PluralFormat(Locale locale, PluralType type) { this(ULocale.forLocale(locale), type); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given pattern string. * The default <code>FORMAT</code> locale will be used to get the set of plural rules and for * standard number formatting. * @param pattern the pattern for this <code>PluralFormat</code>. * @throws IllegalArgumentException if the pattern is invalid. * @see Category#FORMAT */ public PluralFormat(String pattern) { init(null, PluralType.CARDINAL, ULocale.getDefault(Category.FORMAT), null); applyPattern(pattern); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given pattern string and * locale. * The locale will be used to get the set of plural rules and for * standard number formatting. * <p>Example code:{@sample external/icu/android_icu4j/src/samples/java/android/icu/samples/text/pluralformat/PluralFormatSample.java PluralFormatExample} * @param ulocale the <code>PluralFormat</code> will be configured with * rules for this locale. This locale will also be used for standard * number formatting. * @param pattern the pattern for this <code>PluralFormat</code>. * @throws IllegalArgumentException if the pattern is invalid. */ public PluralFormat(ULocale ulocale, String pattern) { init(null, PluralType.CARDINAL, ulocale, null); applyPattern(pattern); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given set of rules and a * pattern. * The standard number formatting will be done using the default <code>FORMAT</code> locale. * @param rules defines the behavior of the <code>PluralFormat</code> * object. * @param pattern the pattern for this <code>PluralFormat</code>. * @throws IllegalArgumentException if the pattern is invalid. * @see Category#FORMAT */ public PluralFormat(PluralRules rules, String pattern) { init(rules, PluralType.CARDINAL, ULocale.getDefault(Category.FORMAT), null); applyPattern(pattern); } /** * Creates a new cardinal-number <code>PluralFormat</code> for a given set of rules, a * pattern and a locale. * @param ulocale the <code>PluralFormat</code> will be configured with * rules for this locale. This locale will also be used for standard * number formatting. * @param rules defines the behavior of the <code>PluralFormat</code> * object. * @param pattern the pattern for this <code>PluralFormat</code>. * @throws IllegalArgumentException if the pattern is invalid. */ public PluralFormat(ULocale ulocale, PluralRules rules, String pattern) { init(rules, PluralType.CARDINAL, ulocale, null); applyPattern(pattern); } /** * Creates a new <code>PluralFormat</code> for a plural type, a * pattern and a locale. * @param ulocale the <code>PluralFormat</code> will be configured with * rules for this locale. This locale will also be used for standard * number formatting. * @param type The plural type (e.g., cardinal or ordinal). * @param pattern the pattern for this <code>PluralFormat</code>. * @throws IllegalArgumentException if the pattern is invalid. */ public PluralFormat(ULocale ulocale, PluralType type, String pattern) { init(null, type, ulocale, null); applyPattern(pattern); } /** * Creates a new <code>PluralFormat</code> for a plural type, a * pattern and a locale. * @param ulocale the <code>PluralFormat</code> will be configured with * rules for this locale. This locale will also be used for standard * number formatting. * @param type The plural type (e.g., cardinal or ordinal). * @param pattern the pattern for this <code>PluralFormat</code>. * @param numberFormat The number formatter to use. * @throws IllegalArgumentException if the pattern is invalid. */ /*package*/ PluralFormat(ULocale ulocale, PluralType type, String pattern, NumberFormat numberFormat) { init(null, type, ulocale, numberFormat); applyPattern(pattern); } /* * Initializes the <code>PluralRules</code> object. * Postcondition:<br/> * <code>ulocale</code> : is <code>locale</code><br/> * <code>pluralRules</code>: if <code>rules</code> != <code>null</code> * it's set to rules, otherwise it is the * predefined plural rule set for the locale * <code>ulocale</code>.<br/> * <code>parsedValues</code>: is <code>null</code><br/> * <code>pattern</code>: is <code>null</code><br/> * <code>numberFormat</code>: a <code>NumberFormat</code> for the locale * <code>ulocale</code>. */ private void init(PluralRules rules, PluralType type, ULocale locale, NumberFormat numberFormat) { ulocale = locale; pluralRules = (rules == null) ? PluralRules.forLocale(ulocale, type) : rules; resetPattern(); this.numberFormat = (numberFormat == null) ? NumberFormat.getInstance(ulocale) : numberFormat; } private void resetPattern() { pattern = null; if(msgPattern != null) { msgPattern.clear(); } offset = 0; } /** * Sets the pattern used by this plural format. * The method parses the pattern and creates a map of format strings * for the plural rules. * Patterns and their interpretation are specified in the class description. * * @param pattern the pattern for this plural format. * @throws IllegalArgumentException if the pattern is invalid. */ public void applyPattern(String pattern) { this.pattern = pattern; if (msgPattern == null) { msgPattern = new MessagePattern(); } try { msgPattern.parsePluralStyle(pattern); offset = msgPattern.getPluralOffset(0); } catch(RuntimeException e) { resetPattern(); throw e; } } /** * Returns the pattern for this PluralFormat. * * @return the pattern string */ public String toPattern() { return pattern; } /** * Finds the PluralFormat sub-message for the given number, or the "other" sub-message. * @param pattern A MessagePattern. * @param partIndex the index of the first PluralFormat argument style part. * @param selector the PluralSelector for mapping the number (minus offset) to a keyword. * @param context worker object for the selector. * @param number a number to be matched to one of the PluralFormat argument's explicit values, * or mapped via the PluralSelector. * @return the sub-message start part index. */ /*package*/ static int findSubMessage( MessagePattern pattern, int partIndex, PluralSelector selector, Object context, double number) { int count=pattern.countParts(); double offset; MessagePattern.Part part=pattern.getPart(partIndex); if(part.getType().hasNumericValue()) { offset=pattern.getNumericValue(part); ++partIndex; } else { offset=0; } // The keyword is null until we need to match against a non-explicit, not-"other" value. // Then we get the keyword from the selector. // (In other words, we never call the selector if we match against an explicit value, // or if the only non-explicit keyword is "other".) String keyword=null; // When we find a match, we set msgStart>0 and also set this boolean to true // to avoid matching the keyword again (duplicates are allowed) // while we continue to look for an explicit-value match. boolean haveKeywordMatch=false; // msgStart is 0 until we find any appropriate sub-message. // We remember the first "other" sub-message if we have not seen any // appropriate sub-message before. // We remember the first matching-keyword sub-message if we have not seen // one of those before. // (The parser allows [does not check for] duplicate keywords. // We just have to make sure to take the first one.) // We avoid matching the keyword twice by also setting haveKeywordMatch=true // at the first keyword match. // We keep going until we find an explicit-value match or reach the end of the plural style. int msgStart=0; // Iterate over (ARG_SELECTOR [ARG_INT|ARG_DOUBLE] message) tuples // until ARG_LIMIT or end of plural-only pattern. do { part=pattern.getPart(partIndex++); MessagePattern.Part.Type type=part.getType(); if(type==MessagePattern.Part.Type.ARG_LIMIT) { break; } assert type==MessagePattern.Part.Type.ARG_SELECTOR; // part is an ARG_SELECTOR followed by an optional explicit value, and then a message if(pattern.getPartType(partIndex).hasNumericValue()) { // explicit value like "=2" part=pattern.getPart(partIndex++); if(number==pattern.getNumericValue(part)) { // matches explicit value return partIndex; } } else if(!haveKeywordMatch) { // plural keyword like "few" or "other" // Compare "other" first and call the selector if this is not "other". if(pattern.partSubstringMatches(part, "other")) { if(msgStart==0) { msgStart=partIndex; if(keyword!=null && keyword.equals("other")) { // This is the first "other" sub-message, // and the selected keyword is also "other". // Do not match "other" again. haveKeywordMatch=true; } } } else { if(keyword==null) { keyword=selector.select(context, number-offset); if(msgStart!=0 && keyword.equals("other")) { // We have already seen an "other" sub-message. // Do not match "other" again. haveKeywordMatch=true; // Skip keyword matching but do getLimitPartIndex(). } } if(!haveKeywordMatch && pattern.partSubstringMatches(part, keyword)) { // keyword matches msgStart=partIndex; // Do not match this keyword again. haveKeywordMatch=true; } } } partIndex=pattern.getLimitPartIndex(partIndex); } while(++partIndex<count); return msgStart; } /** * Interface for selecting PluralFormat keywords for numbers. * The PluralRules class was intended to implement this interface, * but there is no public API that uses a PluralSelector, * only MessageFormat and PluralFormat have PluralSelector implementations. * Therefore, PluralRules is not marked to implement this non-public interface, * to avoid confusing users. * @hide draft / provisional / internal are hidden on Android */ /*package*/ interface PluralSelector { /** * Given a number, returns the appropriate PluralFormat keyword. * * @param context worker object for the selector. * @param number The number to be plural-formatted. * @return The selected PluralFormat keyword. */ public String select(Object context, double number); } // See PluralSelector: // We could avoid this adapter class if we made PluralSelector public // (or at least publicly visible) and had PluralRules implement PluralSelector. private final class PluralSelectorAdapter implements PluralSelector { @Override public String select(Object context, double number) { FixedDecimal dec = (FixedDecimal) context; assert dec.source == (dec.isNegative ? -number : number); return pluralRules.select(dec); } } transient private PluralSelectorAdapter pluralRulesWrapper = new PluralSelectorAdapter(); /** * Formats a plural message for a given number. * * @param number a number for which the plural message should be formatted. * If no pattern has been applied to this * <code>PluralFormat</code> object yet, the formatted number will * be returned. * @return the string containing the formatted plural message. */ public final String format(double number) { return format(number, number); } /** * Formats a plural message for a given number and appends the formatted * message to the given <code>StringBuffer</code>. * @param number a number object (instance of <code>Number</code> for which * the plural message should be formatted. If no pattern has been * applied to this <code>PluralFormat</code> object yet, the * formatted number will be returned. * Note: If this object is not an instance of <code>Number</code>, * the <code>toAppendTo</code> will not be modified. * @param toAppendTo the formatted message will be appended to this * <code>StringBuffer</code>. * @param pos will be ignored by this method. * @return the string buffer passed in as toAppendTo, with formatted text * appended. * @throws IllegalArgumentException if number is not an instance of Number */ @Override public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) { if (!(number instanceof Number)) { throw new IllegalArgumentException("'" + number + "' is not a Number"); } Number numberObject = (Number) number; toAppendTo.append(format(numberObject, numberObject.doubleValue())); return toAppendTo; } private String format(Number numberObject, double number) { // If no pattern was applied, return the formatted number. if (msgPattern == null || msgPattern.countParts() == 0) { return numberFormat.format(numberObject); } // Get the appropriate sub-message. // Select it based on the formatted number-offset. double numberMinusOffset = number - offset; String numberString; if (offset == 0) { numberString = numberFormat.format(numberObject); // could be BigDecimal etc. } else { numberString = numberFormat.format(numberMinusOffset); } FixedDecimal dec; if(numberFormat instanceof DecimalFormat) { dec = ((DecimalFormat) numberFormat).getFixedDecimal(numberMinusOffset); } else { dec = new FixedDecimal(numberMinusOffset); } int partIndex = findSubMessage(msgPattern, 0, pluralRulesWrapper, dec, number); // Replace syntactic # signs in the top level of this sub-message // (not in nested arguments) with the formatted number-offset. StringBuilder result = null; int prevIndex = msgPattern.getPart(partIndex).getLimit(); for (;;) { MessagePattern.Part part = msgPattern.getPart(++partIndex); MessagePattern.Part.Type type = part.getType(); int index = part.getIndex(); if (type == MessagePattern.Part.Type.MSG_LIMIT) { if (result == null) { return pattern.substring(prevIndex, index); } else { return result.append(pattern, prevIndex, index).toString(); } } else if (type == MessagePattern.Part.Type.REPLACE_NUMBER || // JDK compatibility mode: Remove SKIP_SYNTAX. (type == MessagePattern.Part.Type.SKIP_SYNTAX && msgPattern.jdkAposMode())) { if (result == null) { result = new StringBuilder(); } result.append(pattern, prevIndex, index); if (type == MessagePattern.Part.Type.REPLACE_NUMBER) { result.append(numberString); } prevIndex = part.getLimit(); } else if (type == MessagePattern.Part.Type.ARG_START) { if (result == null) { result = new StringBuilder(); } result.append(pattern, prevIndex, index); prevIndex = index; partIndex = msgPattern.getLimitPartIndex(partIndex); index = msgPattern.getPart(partIndex).getLimit(); MessagePattern.appendReducedApostrophes(pattern, prevIndex, index, result); prevIndex = index; } } } /** * This method is not yet supported by <code>PluralFormat</code>. * @param text the string to be parsed. * @param parsePosition defines the position where parsing is to begin, * and upon return, the position where parsing left off. If the position * has not changed upon return, then parsing failed. * @return nothing because this method is not yet implemented. * @throws UnsupportedOperationException will always be thrown by this method. */ public Number parse(String text, ParsePosition parsePosition) { // You get number ranges from this. You can't get an exact number. throw new UnsupportedOperationException(); } /** * This method is not yet supported by <code>PluralFormat</code>. * @param source the string to be parsed. * @param pos defines the position where parsing is to begin, * and upon return, the position where parsing left off. If the position * has not changed upon return, then parsing failed. * @return nothing because this method is not yet implemented. * @throws UnsupportedOperationException will always be thrown by this method. */ @Override public Object parseObject(String source, ParsePosition pos) { throw new UnsupportedOperationException(); } /** * This method returns the PluralRules type found from parsing. * @param source the string to be parsed. * @param pos defines the position where parsing is to begin, * and upon return, the position where parsing left off. If the position * is a negative index, then parsing failed. * @return Returns the PluralRules type. For example, it could be "zero", "one", "two", "few", "many" or "other") */ /*package*/ String parseType(String source, RbnfLenientScanner scanner, FieldPosition pos) { // If no pattern was applied, return null. if (msgPattern == null || msgPattern.countParts() == 0) { pos.setBeginIndex(-1); pos.setEndIndex(-1); return null; } int partIndex = 0; int currMatchIndex; int count=msgPattern.countParts(); int startingAt = pos.getBeginIndex(); if (startingAt < 0) { startingAt = 0; } // The keyword is null until we need to match against a non-explicit, not-"other" value. // Then we get the keyword from the selector. // (In other words, we never call the selector if we match against an explicit value, // or if the only non-explicit keyword is "other".) String keyword = null; String matchedWord = null; int matchedIndex = -1; // Iterate over (ARG_SELECTOR ARG_START message ARG_LIMIT) tuples // until the end of the plural-only pattern. while (partIndex < count) { MessagePattern.Part partSelector=msgPattern.getPart(partIndex++); if (partSelector.getType() != MessagePattern.Part.Type.ARG_SELECTOR) { // Bad format continue; } MessagePattern.Part partStart=msgPattern.getPart(partIndex++); if (partStart.getType() != MessagePattern.Part.Type.MSG_START) { // Bad format continue; } MessagePattern.Part partLimit=msgPattern.getPart(partIndex++); if (partLimit.getType() != MessagePattern.Part.Type.MSG_LIMIT) { // Bad format continue; } String currArg = pattern.substring(partStart.getLimit(), partLimit.getIndex()); if (scanner != null) { // If lenient parsing is turned ON, we've got some time consuming parsing ahead of us. int[] scannerMatchResult = scanner.findText(source, currArg, startingAt); currMatchIndex = scannerMatchResult[0]; } else { currMatchIndex = source.indexOf(currArg, startingAt); } if (currMatchIndex >= 0 && currMatchIndex >= matchedIndex && (matchedWord == null || currArg.length() > matchedWord.length())) { matchedIndex = currMatchIndex; matchedWord = currArg; keyword = pattern.substring(partStart.getLimit(), partLimit.getIndex()); } } if (keyword != null) { pos.setBeginIndex(matchedIndex); pos.setEndIndex(matchedIndex + matchedWord.length()); return keyword; } // Not found! pos.setBeginIndex(-1); pos.setEndIndex(-1); return null; } /** * Sets the locale used by this <code>PluraFormat</code> object. * Note: Calling this method resets this <code>PluraFormat</code> object, * i.e., a pattern that was applied previously will be removed, * and the NumberFormat is set to the default number format for * the locale. The resulting format behaves the same as one * constructed from {@link #PluralFormat(ULocale, PluralRules.PluralType)} * with PluralType.CARDINAL. * @param ulocale the <code>ULocale</code> used to configure the * formatter. If <code>ulocale</code> is <code>null</code>, the * default <code>FORMAT</code> locale will be used. * @see Category#FORMAT * @deprecated ICU 50 This method clears the pattern and might create * a different kind of PluralRules instance; * use one of the constructors to create a new instance instead. * @hide original deprecated declaration */ @Deprecated public void setLocale(ULocale ulocale) { if (ulocale == null) { ulocale = ULocale.getDefault(Category.FORMAT); } init(null, PluralType.CARDINAL, ulocale, null); } /** * Sets the number format used by this formatter. You only need to * call this if you want a different number format than the default * formatter for the locale. * @param format the number format to use. */ public void setNumberFormat(NumberFormat format) { numberFormat = format; } /** * {@inheritDoc} */ @Override public boolean equals(Object rhs) { if(this == rhs) { return true; } if(rhs == null || getClass() != rhs.getClass()) { return false; } PluralFormat pf = (PluralFormat)rhs; return Utility.objectEquals(ulocale, pf.ulocale) && Utility.objectEquals(pluralRules, pf.pluralRules) && Utility.objectEquals(msgPattern, pf.msgPattern) && Utility.objectEquals(numberFormat, pf.numberFormat); } /** * Returns true if this equals the provided PluralFormat. * @param rhs the PluralFormat to compare against * @return true if this equals rhs */ public boolean equals(PluralFormat rhs) { return equals((Object)rhs); } /** * {@inheritDoc} */ @Override public int hashCode() { return pluralRules.hashCode() ^ parsedValues.hashCode(); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("locale=" + ulocale); buf.append(", rules='" + pluralRules + "'"); buf.append(", pattern='" + pattern + "'"); buf.append(", format='" + numberFormat + "'"); return buf.toString(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); pluralRulesWrapper = new PluralSelectorAdapter(); // Ignore the parsedValues from an earlier class version (before ICU 4.8) // and rebuild the msgPattern. parsedValues = null; if (pattern != null) { applyPattern(pattern); } } }
googleapis/google-cloud-java
36,335
java-chronicle/proto-google-cloud-chronicle-v1/src/main/java/com/google/cloud/chronicle/v1/ListRetrohuntsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/chronicle/v1/rule.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.chronicle.v1; /** * * * <pre> * Request message for ListRetrohunts method. * </pre> * * Protobuf type {@code google.cloud.chronicle.v1.ListRetrohuntsRequest} */ public final class ListRetrohuntsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.chronicle.v1.ListRetrohuntsRequest) ListRetrohuntsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListRetrohuntsRequest.newBuilder() to construct. private ListRetrohuntsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListRetrohuntsRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListRetrohuntsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.chronicle.v1.RuleProto .internal_static_google_cloud_chronicle_v1_ListRetrohuntsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.chronicle.v1.RuleProto .internal_static_google_cloud_chronicle_v1_ListRetrohuntsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.chronicle.v1.ListRetrohuntsRequest.class, com.google.cloud.chronicle.v1.ListRetrohuntsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The rule that the retrohunts belong to. * Format: * `projects/{project}/locations/{location}/instances/{instance}/rules/{rule}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The rule that the retrohunts belong to. * Format: * `projects/{project}/locations/{location}/instances/{instance}/rules/{rule}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * The maximum number of retrohunt to return. The service may return fewer * than this value. If unspecified, at most 100 retrohunts will be returned. * The maximum value is 1000; values above 1000 will be coerced to * 1000. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A page token, received from a previous `ListRetrohunts` call. * Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `ListRetrohunts` must * match the call that provided the page token. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A page token, received from a previous `ListRetrohunts` call. * Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `ListRetrohunts` must * match the call that provided the page token. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * A filter that can be used to retrieve specific rule deployments. * The following fields are filterable: * state * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * A filter that can be used to retrieve specific rule deployments. * The following fields are filterable: * state * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.chronicle.v1.ListRetrohuntsRequest)) { return super.equals(obj); } com.google.cloud.chronicle.v1.ListRetrohuntsRequest other = (com.google.cloud.chronicle.v1.ListRetrohuntsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.chronicle.v1.ListRetrohuntsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for ListRetrohunts method. * </pre> * * Protobuf type {@code google.cloud.chronicle.v1.ListRetrohuntsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.chronicle.v1.ListRetrohuntsRequest) com.google.cloud.chronicle.v1.ListRetrohuntsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.chronicle.v1.RuleProto .internal_static_google_cloud_chronicle_v1_ListRetrohuntsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.chronicle.v1.RuleProto .internal_static_google_cloud_chronicle_v1_ListRetrohuntsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.chronicle.v1.ListRetrohuntsRequest.class, com.google.cloud.chronicle.v1.ListRetrohuntsRequest.Builder.class); } // Construct using com.google.cloud.chronicle.v1.ListRetrohuntsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.chronicle.v1.RuleProto .internal_static_google_cloud_chronicle_v1_ListRetrohuntsRequest_descriptor; } @java.lang.Override public com.google.cloud.chronicle.v1.ListRetrohuntsRequest getDefaultInstanceForType() { return com.google.cloud.chronicle.v1.ListRetrohuntsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.chronicle.v1.ListRetrohuntsRequest build() { com.google.cloud.chronicle.v1.ListRetrohuntsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.chronicle.v1.ListRetrohuntsRequest buildPartial() { com.google.cloud.chronicle.v1.ListRetrohuntsRequest result = new com.google.cloud.chronicle.v1.ListRetrohuntsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.chronicle.v1.ListRetrohuntsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.chronicle.v1.ListRetrohuntsRequest) { return mergeFrom((com.google.cloud.chronicle.v1.ListRetrohuntsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.chronicle.v1.ListRetrohuntsRequest other) { if (other == com.google.cloud.chronicle.v1.ListRetrohuntsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The rule that the retrohunts belong to. * Format: * `projects/{project}/locations/{location}/instances/{instance}/rules/{rule}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The rule that the retrohunts belong to. * Format: * `projects/{project}/locations/{location}/instances/{instance}/rules/{rule}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The rule that the retrohunts belong to. * Format: * `projects/{project}/locations/{location}/instances/{instance}/rules/{rule}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The rule that the retrohunts belong to. * Format: * `projects/{project}/locations/{location}/instances/{instance}/rules/{rule}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The rule that the retrohunts belong to. * Format: * `projects/{project}/locations/{location}/instances/{instance}/rules/{rule}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * The maximum number of retrohunt to return. The service may return fewer * than this value. If unspecified, at most 100 retrohunts will be returned. * The maximum value is 1000; values above 1000 will be coerced to * 1000. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * The maximum number of retrohunt to return. The service may return fewer * than this value. If unspecified, at most 100 retrohunts will be returned. * The maximum value is 1000; values above 1000 will be coerced to * 1000. * </pre> * * <code>int32 page_size = 2;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The maximum number of retrohunt to return. The service may return fewer * than this value. If unspecified, at most 100 retrohunts will be returned. * The maximum value is 1000; values above 1000 will be coerced to * 1000. * </pre> * * <code>int32 page_size = 2;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A page token, received from a previous `ListRetrohunts` call. * Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `ListRetrohunts` must * match the call that provided the page token. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A page token, received from a previous `ListRetrohunts` call. * Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `ListRetrohunts` must * match the call that provided the page token. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A page token, received from a previous `ListRetrohunts` call. * Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `ListRetrohunts` must * match the call that provided the page token. * </pre> * * <code>string page_token = 3;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A page token, received from a previous `ListRetrohunts` call. * Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `ListRetrohunts` must * match the call that provided the page token. * </pre> * * <code>string page_token = 3;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A page token, received from a previous `ListRetrohunts` call. * Provide this to retrieve the subsequent page. * * When paginating, all other parameters provided to `ListRetrohunts` must * match the call that provided the page token. * </pre> * * <code>string page_token = 3;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * A filter that can be used to retrieve specific rule deployments. * The following fields are filterable: * state * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A filter that can be used to retrieve specific rule deployments. * The following fields are filterable: * state * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A filter that can be used to retrieve specific rule deployments. * The following fields are filterable: * state * </pre> * * <code>string filter = 4;</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * A filter that can be used to retrieve specific rule deployments. * The following fields are filterable: * state * </pre> * * <code>string filter = 4;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * A filter that can be used to retrieve specific rule deployments. * The following fields are filterable: * state * </pre> * * <code>string filter = 4;</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.chronicle.v1.ListRetrohuntsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.chronicle.v1.ListRetrohuntsRequest) private static final com.google.cloud.chronicle.v1.ListRetrohuntsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.chronicle.v1.ListRetrohuntsRequest(); } public static com.google.cloud.chronicle.v1.ListRetrohuntsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListRetrohuntsRequest> PARSER = new com.google.protobuf.AbstractParser<ListRetrohuntsRequest>() { @java.lang.Override public ListRetrohuntsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListRetrohuntsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListRetrohuntsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.chronicle.v1.ListRetrohuntsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,451
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ResourceRuntimeSpec.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/persistent_resource.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Configuration for the runtime on a PersistentResource instance, including * but not limited to: * * * Service accounts used to run the workloads. * * Whether to make it a dedicated Ray Cluster. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec} */ public final class ResourceRuntimeSpec extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec) ResourceRuntimeSpecOrBuilder { private static final long serialVersionUID = 0L; // Use ResourceRuntimeSpec.newBuilder() to construct. private ResourceRuntimeSpec(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ResourceRuntimeSpec() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ResourceRuntimeSpec(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.PersistentResourceProto .internal_static_google_cloud_aiplatform_v1beta1_ResourceRuntimeSpec_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.PersistentResourceProto .internal_static_google_cloud_aiplatform_v1beta1_ResourceRuntimeSpec_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec.class, com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec.Builder.class); } private int bitField0_; public static final int SERVICE_ACCOUNT_SPEC_FIELD_NUMBER = 2; private com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec serviceAccountSpec_; /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the serviceAccountSpec field is set. */ @java.lang.Override public boolean hasServiceAccountSpec() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The serviceAccountSpec. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec getServiceAccountSpec() { return serviceAccountSpec_ == null ? com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.getDefaultInstance() : serviceAccountSpec_; } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ServiceAccountSpecOrBuilder getServiceAccountSpecOrBuilder() { return serviceAccountSpec_ == null ? com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.getDefaultInstance() : serviceAccountSpec_; } public static final int RAY_SPEC_FIELD_NUMBER = 1; private com.google.cloud.aiplatform.v1beta1.RaySpec raySpec_; /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the raySpec field is set. */ @java.lang.Override public boolean hasRaySpec() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The raySpec. */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RaySpec getRaySpec() { return raySpec_ == null ? com.google.cloud.aiplatform.v1beta1.RaySpec.getDefaultInstance() : raySpec_; } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.RaySpecOrBuilder getRaySpecOrBuilder() { return raySpec_ == null ? com.google.cloud.aiplatform.v1beta1.RaySpec.getDefaultInstance() : raySpec_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(1, getRaySpec()); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getServiceAccountSpec()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getRaySpec()); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getServiceAccountSpec()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec other = (com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec) obj; if (hasServiceAccountSpec() != other.hasServiceAccountSpec()) return false; if (hasServiceAccountSpec()) { if (!getServiceAccountSpec().equals(other.getServiceAccountSpec())) return false; } if (hasRaySpec() != other.hasRaySpec()) return false; if (hasRaySpec()) { if (!getRaySpec().equals(other.getRaySpec())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasServiceAccountSpec()) { hash = (37 * hash) + SERVICE_ACCOUNT_SPEC_FIELD_NUMBER; hash = (53 * hash) + getServiceAccountSpec().hashCode(); } if (hasRaySpec()) { hash = (37 * hash) + RAY_SPEC_FIELD_NUMBER; hash = (53 * hash) + getRaySpec().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Configuration for the runtime on a PersistentResource instance, including * but not limited to: * * * Service accounts used to run the workloads. * * Whether to make it a dedicated Ray Cluster. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec) com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpecOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.PersistentResourceProto .internal_static_google_cloud_aiplatform_v1beta1_ResourceRuntimeSpec_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.PersistentResourceProto .internal_static_google_cloud_aiplatform_v1beta1_ResourceRuntimeSpec_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec.class, com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getServiceAccountSpecFieldBuilder(); getRaySpecFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; serviceAccountSpec_ = null; if (serviceAccountSpecBuilder_ != null) { serviceAccountSpecBuilder_.dispose(); serviceAccountSpecBuilder_ = null; } raySpec_ = null; if (raySpecBuilder_ != null) { raySpecBuilder_.dispose(); raySpecBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.PersistentResourceProto .internal_static_google_cloud_aiplatform_v1beta1_ResourceRuntimeSpec_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec build() { com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec buildPartial() { com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec result = new com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.serviceAccountSpec_ = serviceAccountSpecBuilder_ == null ? serviceAccountSpec_ : serviceAccountSpecBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.raySpec_ = raySpecBuilder_ == null ? raySpec_ : raySpecBuilder_.build(); to_bitField0_ |= 0x00000002; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec other) { if (other == com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec.getDefaultInstance()) return this; if (other.hasServiceAccountSpec()) { mergeServiceAccountSpec(other.getServiceAccountSpec()); } if (other.hasRaySpec()) { mergeRaySpec(other.getRaySpec()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getRaySpecFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 10 case 18: { input.readMessage( getServiceAccountSpecFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec serviceAccountSpec_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec, com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.Builder, com.google.cloud.aiplatform.v1beta1.ServiceAccountSpecOrBuilder> serviceAccountSpecBuilder_; /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the serviceAccountSpec field is set. */ public boolean hasServiceAccountSpec() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The serviceAccountSpec. */ public com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec getServiceAccountSpec() { if (serviceAccountSpecBuilder_ == null) { return serviceAccountSpec_ == null ? com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.getDefaultInstance() : serviceAccountSpec_; } else { return serviceAccountSpecBuilder_.getMessage(); } } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setServiceAccountSpec( com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec value) { if (serviceAccountSpecBuilder_ == null) { if (value == null) { throw new NullPointerException(); } serviceAccountSpec_ = value; } else { serviceAccountSpecBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setServiceAccountSpec( com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.Builder builderForValue) { if (serviceAccountSpecBuilder_ == null) { serviceAccountSpec_ = builderForValue.build(); } else { serviceAccountSpecBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeServiceAccountSpec( com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec value) { if (serviceAccountSpecBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && serviceAccountSpec_ != null && serviceAccountSpec_ != com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.getDefaultInstance()) { getServiceAccountSpecBuilder().mergeFrom(value); } else { serviceAccountSpec_ = value; } } else { serviceAccountSpecBuilder_.mergeFrom(value); } if (serviceAccountSpec_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearServiceAccountSpec() { bitField0_ = (bitField0_ & ~0x00000001); serviceAccountSpec_ = null; if (serviceAccountSpecBuilder_ != null) { serviceAccountSpecBuilder_.dispose(); serviceAccountSpecBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.Builder getServiceAccountSpecBuilder() { bitField0_ |= 0x00000001; onChanged(); return getServiceAccountSpecFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1beta1.ServiceAccountSpecOrBuilder getServiceAccountSpecOrBuilder() { if (serviceAccountSpecBuilder_ != null) { return serviceAccountSpecBuilder_.getMessageOrBuilder(); } else { return serviceAccountSpec_ == null ? com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.getDefaultInstance() : serviceAccountSpec_; } } /** * * * <pre> * Optional. Configure the use of workload identity on the PersistentResource * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.ServiceAccountSpec service_account_spec = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec, com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.Builder, com.google.cloud.aiplatform.v1beta1.ServiceAccountSpecOrBuilder> getServiceAccountSpecFieldBuilder() { if (serviceAccountSpecBuilder_ == null) { serviceAccountSpecBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec, com.google.cloud.aiplatform.v1beta1.ServiceAccountSpec.Builder, com.google.cloud.aiplatform.v1beta1.ServiceAccountSpecOrBuilder>( getServiceAccountSpec(), getParentForChildren(), isClean()); serviceAccountSpec_ = null; } return serviceAccountSpecBuilder_; } private com.google.cloud.aiplatform.v1beta1.RaySpec raySpec_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RaySpec, com.google.cloud.aiplatform.v1beta1.RaySpec.Builder, com.google.cloud.aiplatform.v1beta1.RaySpecOrBuilder> raySpecBuilder_; /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the raySpec field is set. */ public boolean hasRaySpec() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The raySpec. */ public com.google.cloud.aiplatform.v1beta1.RaySpec getRaySpec() { if (raySpecBuilder_ == null) { return raySpec_ == null ? com.google.cloud.aiplatform.v1beta1.RaySpec.getDefaultInstance() : raySpec_; } else { return raySpecBuilder_.getMessage(); } } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setRaySpec(com.google.cloud.aiplatform.v1beta1.RaySpec value) { if (raySpecBuilder_ == null) { if (value == null) { throw new NullPointerException(); } raySpec_ = value; } else { raySpecBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setRaySpec(com.google.cloud.aiplatform.v1beta1.RaySpec.Builder builderForValue) { if (raySpecBuilder_ == null) { raySpec_ = builderForValue.build(); } else { raySpecBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeRaySpec(com.google.cloud.aiplatform.v1beta1.RaySpec value) { if (raySpecBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && raySpec_ != null && raySpec_ != com.google.cloud.aiplatform.v1beta1.RaySpec.getDefaultInstance()) { getRaySpecBuilder().mergeFrom(value); } else { raySpec_ = value; } } else { raySpecBuilder_.mergeFrom(value); } if (raySpec_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearRaySpec() { bitField0_ = (bitField0_ & ~0x00000002); raySpec_ = null; if (raySpecBuilder_ != null) { raySpecBuilder_.dispose(); raySpecBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1beta1.RaySpec.Builder getRaySpecBuilder() { bitField0_ |= 0x00000002; onChanged(); return getRaySpecFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1beta1.RaySpecOrBuilder getRaySpecOrBuilder() { if (raySpecBuilder_ != null) { return raySpecBuilder_.getMessageOrBuilder(); } else { return raySpec_ == null ? com.google.cloud.aiplatform.v1beta1.RaySpec.getDefaultInstance() : raySpec_; } } /** * * * <pre> * Optional. Ray cluster configuration. * Required when creating a dedicated RayCluster on the PersistentResource. * </pre> * * <code> * .google.cloud.aiplatform.v1beta1.RaySpec ray_spec = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RaySpec, com.google.cloud.aiplatform.v1beta1.RaySpec.Builder, com.google.cloud.aiplatform.v1beta1.RaySpecOrBuilder> getRaySpecFieldBuilder() { if (raySpecBuilder_ == null) { raySpecBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.RaySpec, com.google.cloud.aiplatform.v1beta1.RaySpec.Builder, com.google.cloud.aiplatform.v1beta1.RaySpecOrBuilder>( getRaySpec(), getParentForChildren(), isClean()); raySpec_ = null; } return raySpecBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec) private static final com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec(); } public static com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ResourceRuntimeSpec> PARSER = new com.google.protobuf.AbstractParser<ResourceRuntimeSpec>() { @java.lang.Override public ResourceRuntimeSpec parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ResourceRuntimeSpec> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ResourceRuntimeSpec> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ResourceRuntimeSpec getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,495
java-alloydb/proto-google-cloud-alloydb-v1alpha/src/main/java/com/google/cloud/alloydb/v1alpha/CreateInstanceRequests.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/alloydb/v1alpha/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.alloydb.v1alpha; /** * * * <pre> * See usage below for notes. * </pre> * * Protobuf type {@code google.cloud.alloydb.v1alpha.CreateInstanceRequests} */ public final class CreateInstanceRequests extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.alloydb.v1alpha.CreateInstanceRequests) CreateInstanceRequestsOrBuilder { private static final long serialVersionUID = 0L; // Use CreateInstanceRequests.newBuilder() to construct. private CreateInstanceRequests(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateInstanceRequests() { createInstanceRequests_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateInstanceRequests(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_CreateInstanceRequests_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_CreateInstanceRequests_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.alloydb.v1alpha.CreateInstanceRequests.class, com.google.cloud.alloydb.v1alpha.CreateInstanceRequests.Builder.class); } public static final int CREATE_INSTANCE_REQUESTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.alloydb.v1alpha.CreateInstanceRequest> createInstanceRequests_; /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.alloydb.v1alpha.CreateInstanceRequest> getCreateInstanceRequestsList() { return createInstanceRequests_; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.alloydb.v1alpha.CreateInstanceRequestOrBuilder> getCreateInstanceRequestsOrBuilderList() { return createInstanceRequests_; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public int getCreateInstanceRequestsCount() { return createInstanceRequests_.size(); } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.alloydb.v1alpha.CreateInstanceRequest getCreateInstanceRequests( int index) { return createInstanceRequests_.get(index); } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.alloydb.v1alpha.CreateInstanceRequestOrBuilder getCreateInstanceRequestsOrBuilder(int index) { return createInstanceRequests_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < createInstanceRequests_.size(); i++) { output.writeMessage(1, createInstanceRequests_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < createInstanceRequests_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, createInstanceRequests_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.alloydb.v1alpha.CreateInstanceRequests)) { return super.equals(obj); } com.google.cloud.alloydb.v1alpha.CreateInstanceRequests other = (com.google.cloud.alloydb.v1alpha.CreateInstanceRequests) obj; if (!getCreateInstanceRequestsList().equals(other.getCreateInstanceRequestsList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getCreateInstanceRequestsCount() > 0) { hash = (37 * hash) + CREATE_INSTANCE_REQUESTS_FIELD_NUMBER; hash = (53 * hash) + getCreateInstanceRequestsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.alloydb.v1alpha.CreateInstanceRequests prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * See usage below for notes. * </pre> * * Protobuf type {@code google.cloud.alloydb.v1alpha.CreateInstanceRequests} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.alloydb.v1alpha.CreateInstanceRequests) com.google.cloud.alloydb.v1alpha.CreateInstanceRequestsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_CreateInstanceRequests_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_CreateInstanceRequests_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.alloydb.v1alpha.CreateInstanceRequests.class, com.google.cloud.alloydb.v1alpha.CreateInstanceRequests.Builder.class); } // Construct using com.google.cloud.alloydb.v1alpha.CreateInstanceRequests.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (createInstanceRequestsBuilder_ == null) { createInstanceRequests_ = java.util.Collections.emptyList(); } else { createInstanceRequests_ = null; createInstanceRequestsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_CreateInstanceRequests_descriptor; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.CreateInstanceRequests getDefaultInstanceForType() { return com.google.cloud.alloydb.v1alpha.CreateInstanceRequests.getDefaultInstance(); } @java.lang.Override public com.google.cloud.alloydb.v1alpha.CreateInstanceRequests build() { com.google.cloud.alloydb.v1alpha.CreateInstanceRequests result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.CreateInstanceRequests buildPartial() { com.google.cloud.alloydb.v1alpha.CreateInstanceRequests result = new com.google.cloud.alloydb.v1alpha.CreateInstanceRequests(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.alloydb.v1alpha.CreateInstanceRequests result) { if (createInstanceRequestsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { createInstanceRequests_ = java.util.Collections.unmodifiableList(createInstanceRequests_); bitField0_ = (bitField0_ & ~0x00000001); } result.createInstanceRequests_ = createInstanceRequests_; } else { result.createInstanceRequests_ = createInstanceRequestsBuilder_.build(); } } private void buildPartial0(com.google.cloud.alloydb.v1alpha.CreateInstanceRequests result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.alloydb.v1alpha.CreateInstanceRequests) { return mergeFrom((com.google.cloud.alloydb.v1alpha.CreateInstanceRequests) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.alloydb.v1alpha.CreateInstanceRequests other) { if (other == com.google.cloud.alloydb.v1alpha.CreateInstanceRequests.getDefaultInstance()) return this; if (createInstanceRequestsBuilder_ == null) { if (!other.createInstanceRequests_.isEmpty()) { if (createInstanceRequests_.isEmpty()) { createInstanceRequests_ = other.createInstanceRequests_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.addAll(other.createInstanceRequests_); } onChanged(); } } else { if (!other.createInstanceRequests_.isEmpty()) { if (createInstanceRequestsBuilder_.isEmpty()) { createInstanceRequestsBuilder_.dispose(); createInstanceRequestsBuilder_ = null; createInstanceRequests_ = other.createInstanceRequests_; bitField0_ = (bitField0_ & ~0x00000001); createInstanceRequestsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCreateInstanceRequestsFieldBuilder() : null; } else { createInstanceRequestsBuilder_.addAllMessages(other.createInstanceRequests_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.alloydb.v1alpha.CreateInstanceRequest m = input.readMessage( com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.parser(), extensionRegistry); if (createInstanceRequestsBuilder_ == null) { ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.add(m); } else { createInstanceRequestsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.alloydb.v1alpha.CreateInstanceRequest> createInstanceRequests_ = java.util.Collections.emptyList(); private void ensureCreateInstanceRequestsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { createInstanceRequests_ = new java.util.ArrayList<com.google.cloud.alloydb.v1alpha.CreateInstanceRequest>( createInstanceRequests_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.alloydb.v1alpha.CreateInstanceRequest, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder, com.google.cloud.alloydb.v1alpha.CreateInstanceRequestOrBuilder> createInstanceRequestsBuilder_; /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.alloydb.v1alpha.CreateInstanceRequest> getCreateInstanceRequestsList() { if (createInstanceRequestsBuilder_ == null) { return java.util.Collections.unmodifiableList(createInstanceRequests_); } else { return createInstanceRequestsBuilder_.getMessageList(); } } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public int getCreateInstanceRequestsCount() { if (createInstanceRequestsBuilder_ == null) { return createInstanceRequests_.size(); } else { return createInstanceRequestsBuilder_.getCount(); } } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.alloydb.v1alpha.CreateInstanceRequest getCreateInstanceRequests( int index) { if (createInstanceRequestsBuilder_ == null) { return createInstanceRequests_.get(index); } else { return createInstanceRequestsBuilder_.getMessage(index); } } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setCreateInstanceRequests( int index, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest value) { if (createInstanceRequestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.set(index, value); onChanged(); } else { createInstanceRequestsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setCreateInstanceRequests( int index, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder builderForValue) { if (createInstanceRequestsBuilder_ == null) { ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.set(index, builderForValue.build()); onChanged(); } else { createInstanceRequestsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addCreateInstanceRequests( com.google.cloud.alloydb.v1alpha.CreateInstanceRequest value) { if (createInstanceRequestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.add(value); onChanged(); } else { createInstanceRequestsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addCreateInstanceRequests( int index, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest value) { if (createInstanceRequestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.add(index, value); onChanged(); } else { createInstanceRequestsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addCreateInstanceRequests( com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder builderForValue) { if (createInstanceRequestsBuilder_ == null) { ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.add(builderForValue.build()); onChanged(); } else { createInstanceRequestsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addCreateInstanceRequests( int index, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder builderForValue) { if (createInstanceRequestsBuilder_ == null) { ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.add(index, builderForValue.build()); onChanged(); } else { createInstanceRequestsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addAllCreateInstanceRequests( java.lang.Iterable<? extends com.google.cloud.alloydb.v1alpha.CreateInstanceRequest> values) { if (createInstanceRequestsBuilder_ == null) { ensureCreateInstanceRequestsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, createInstanceRequests_); onChanged(); } else { createInstanceRequestsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearCreateInstanceRequests() { if (createInstanceRequestsBuilder_ == null) { createInstanceRequests_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { createInstanceRequestsBuilder_.clear(); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder removeCreateInstanceRequests(int index) { if (createInstanceRequestsBuilder_ == null) { ensureCreateInstanceRequestsIsMutable(); createInstanceRequests_.remove(index); onChanged(); } else { createInstanceRequestsBuilder_.remove(index); } return this; } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder getCreateInstanceRequestsBuilder(int index) { return getCreateInstanceRequestsFieldBuilder().getBuilder(index); } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.alloydb.v1alpha.CreateInstanceRequestOrBuilder getCreateInstanceRequestsOrBuilder(int index) { if (createInstanceRequestsBuilder_ == null) { return createInstanceRequests_.get(index); } else { return createInstanceRequestsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<? extends com.google.cloud.alloydb.v1alpha.CreateInstanceRequestOrBuilder> getCreateInstanceRequestsOrBuilderList() { if (createInstanceRequestsBuilder_ != null) { return createInstanceRequestsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(createInstanceRequests_); } } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder addCreateInstanceRequestsBuilder() { return getCreateInstanceRequestsFieldBuilder() .addBuilder(com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.getDefaultInstance()); } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder addCreateInstanceRequestsBuilder(int index) { return getCreateInstanceRequestsFieldBuilder() .addBuilder( index, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.getDefaultInstance()); } /** * * * <pre> * Required. Primary and read replica instances to be created. This list * should not be empty. * </pre> * * <code> * repeated .google.cloud.alloydb.v1alpha.CreateInstanceRequest create_instance_requests = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder> getCreateInstanceRequestsBuilderList() { return getCreateInstanceRequestsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.alloydb.v1alpha.CreateInstanceRequest, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder, com.google.cloud.alloydb.v1alpha.CreateInstanceRequestOrBuilder> getCreateInstanceRequestsFieldBuilder() { if (createInstanceRequestsBuilder_ == null) { createInstanceRequestsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.alloydb.v1alpha.CreateInstanceRequest, com.google.cloud.alloydb.v1alpha.CreateInstanceRequest.Builder, com.google.cloud.alloydb.v1alpha.CreateInstanceRequestOrBuilder>( createInstanceRequests_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); createInstanceRequests_ = null; } return createInstanceRequestsBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.alloydb.v1alpha.CreateInstanceRequests) } // @@protoc_insertion_point(class_scope:google.cloud.alloydb.v1alpha.CreateInstanceRequests) private static final com.google.cloud.alloydb.v1alpha.CreateInstanceRequests DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.alloydb.v1alpha.CreateInstanceRequests(); } public static com.google.cloud.alloydb.v1alpha.CreateInstanceRequests getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateInstanceRequests> PARSER = new com.google.protobuf.AbstractParser<CreateInstanceRequests>() { @java.lang.Override public CreateInstanceRequests parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<CreateInstanceRequests> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateInstanceRequests> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.CreateInstanceRequests getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
hibernate/hibernate-search
34,156
integrationtest/mapper/orm/src/test/java/org/hibernate/search/integrationtest/mapper/orm/automaticindexing/association/bytype/onetoone/ownedbycontained/AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT.java
/* * SPDX-License-Identifier: Apache-2.0 * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.onetoone.ownedbycontained; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import jakarta.persistence.Basic; import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; import jakarta.persistence.Embedded; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; import jakarta.persistence.OrderColumn; import jakarta.persistence.Transient; import org.hibernate.annotations.LazyGroup; import org.hibernate.cfg.AvailableSettings; import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.AbstractAutomaticIndexingSingleValuedAssociationBaseIT; import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.ContainerPrimitives; import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.accessor.MultiValuedPropertyAccessor; import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.accessor.PropertyAccessor; import org.hibernate.search.mapper.pojo.automaticindexing.ReindexOnUpdate; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.AssociationInverseSide; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.GenericField; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexingDependency; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ObjectPath; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.PropertyValue; import org.hibernate.search.util.impl.integrationtest.mapper.orm.OrmSetupHelper; import org.hibernate.search.util.impl.test.annotation.TestForIssue; import org.hibernate.testing.bytecode.enhancement.EnhancementOptions; import org.hibernate.testing.bytecode.enhancement.extension.BytecodeEnhanced; import org.junit.jupiter.api.Test; /** * Test automatic indexing caused by single-valued association updates * or by updates of associated (contained) entities, * with a {@code @OneToOne} association owned by the contained side, * and with lazy associations on the contained side. */ @BytecodeEnhanced // So that we can have lazy *ToOne associations @EnhancementOptions(lazyLoading = true) @TestForIssue(jiraKey = "HSEARCH-4305") class AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT extends AbstractAutomaticIndexingSingleValuedAssociationBaseIT< AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT.IndexedEntity, AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT.ContainingEntity, AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT.ContainingEmbeddable, AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT.ContainedEntity, AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT.ContainedEmbeddable> { public AutomaticIndexingOneToOneOwnedByContainedLazyOnContainedSideIT() { super( IndexedEntity.PRIMITIVES, ContainingEntity.PRIMITIVES, ContainingEmbeddable.PRIMITIVES, ContainedEntity.PRIMITIVES, ContainedEmbeddable.PRIMITIVES ); } @Override protected boolean isAssociationMultiValuedOnContainedSide() { return false; } @Override protected boolean isAssociationOwnedByContainedSide() { return true; } @Override protected boolean isAssociationLazyOnContainingSide() { return false; } @Override protected OrmSetupHelper.SetupContext additionalSetup(OrmSetupHelper.SetupContext setupContext) { // Avoid problems with deep chains of eager associations in ORM 6 // See https://github.com/hibernate/hibernate-orm/blob/6.0/migration-guide.adoc#fetch-circularity-determination // See https://hibernate.zulipchat.com/#narrow/stream/132094-hibernate-orm-dev/topic/lazy.20associations.20with.20ORM.206 setupContext.withProperty( AvailableSettings.MAX_FETCH_DEPTH, 1 ); // Necessary for BytecodeEnhancerRunner, see BytecodeEnhancementIT.setup setupContext.withTcclLookupPrecedenceBefore(); return setupContext; } @Test void testBytecodeEnhancementWorked() { assertThat( ContainingEntity.class.getDeclaredMethods() ) .extracting( Method::getName ) .anyMatch( name -> name.startsWith( "$$_hibernate_" ) ); } @Entity(name = "containing") public static class ContainingEntity { @Id private Integer id; private String nonIndexedField; @OneToOne(fetch = FetchType.LAZY) private ContainingEntity parent; @OneToOne(mappedBy = "parent", fetch = FetchType.LAZY) @IndexedEmbedded(includePaths = { "containedIndexedEmbedded.indexedField", "containedIndexedEmbedded.indexedElementCollectionField", "containedIndexedEmbedded.containedDerivedField", "containedIndexedEmbeddedShallowReindexOnUpdate.indexedField", "containedIndexedEmbeddedShallowReindexOnUpdate.indexedElementCollectionField", "containedIndexedEmbeddedShallowReindexOnUpdate.containedDerivedField", "containedIndexedEmbeddedNoReindexOnUpdate.indexedField", "containedIndexedEmbeddedNoReindexOnUpdate.indexedElementCollectionField", "containedIndexedEmbeddedNoReindexOnUpdate.containedDerivedField", "containedIndexedEmbeddedWithCast.indexedField", "embeddedAssociations.containedIndexedEmbedded.indexedField", "embeddedAssociations.containedIndexedEmbedded.indexedElementCollectionField", "embeddedAssociations.containedIndexedEmbedded.containedDerivedField", "containedElementCollectionAssociationsIndexedEmbedded.indexedField", "containedElementCollectionAssociationsIndexedEmbedded.indexedElementCollectionField", "containedElementCollectionAssociationsIndexedEmbedded.containedDerivedField", "crossEntityDerivedField" }) private ContainingEntity child; @OneToOne(mappedBy = "containingAsIndexedEmbedded") @IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" }) private ContainedEntity containedIndexedEmbedded; @OneToOne(mappedBy = "containingAsNonIndexedEmbedded") private ContainedEntity containedNonIndexedEmbedded; @OneToOne(mappedBy = "containingAsIndexedEmbeddedShallowReindexOnUpdate") @IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" }) @IndexingDependency(reindexOnUpdate = ReindexOnUpdate.SHALLOW) private ContainedEntity containedIndexedEmbeddedShallowReindexOnUpdate; @OneToOne(mappedBy = "containingAsIndexedEmbeddedNoReindexOnUpdate") @IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" }) @IndexingDependency(reindexOnUpdate = ReindexOnUpdate.NO) private ContainedEntity containedIndexedEmbeddedNoReindexOnUpdate; @OneToOne(mappedBy = "containingAsUsedInCrossEntityDerivedProperty") private ContainedEntity containedUsedInCrossEntityDerivedProperty; @OneToOne(mappedBy = "containingAsIndexedEmbeddedWithCast", targetEntity = ContainedEntity.class) @IndexedEmbedded(includePaths = { "indexedField" }, targetType = ContainedEntity.class) private Object containedIndexedEmbeddedWithCast; @IndexedEmbedded @Embedded private ContainingEmbeddable embeddedAssociations; /* * No mappedBy here. The inverse side of associations within an element collection cannot use mappedBy. * If they do, Hibernate ORM will fail (throw an exception) while attempting to walk down the mappedBy path, * because it assumes the prefix of that path is an embeddable, * and in this case it is a List. * TODO use mappedBy when the above gets fixed in Hibernate ORM */ @OneToOne @JoinColumn(name = "CECAssocIdxEmb") @AssociationInverseSide(inversePath = @ObjectPath({ @PropertyValue(propertyName = "elementCollectionAssociations"), @PropertyValue(propertyName = "containingAsIndexedEmbedded") })) @IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" }) private ContainedEntity containedElementCollectionAssociationsIndexedEmbedded; /* * No mappedBy here. Same reason as just above. * TODO use mappedBy when the above gets fixed in Hibernate ORM */ @OneToOne @JoinColumn(name = "CECAssocNonIdxEmb") @AssociationInverseSide(inversePath = @ObjectPath({ @PropertyValue(propertyName = "elementCollectionAssociations"), @PropertyValue(propertyName = "containingAsNonIndexedEmbedded") })) private ContainedEntity containedElementCollectionAssociationsNonIndexedEmbedded; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNonIndexedField() { return nonIndexedField; } public void setNonIndexedField(String nonIndexedField) { this.nonIndexedField = nonIndexedField; } public ContainingEntity getParent() { return parent; } public void setParent(ContainingEntity parent) { this.parent = parent; } public ContainingEntity getChild() { return child; } public void setChild(ContainingEntity child) { this.child = child; } public ContainedEntity getContainedIndexedEmbedded() { return containedIndexedEmbedded; } public void setContainedIndexedEmbedded(ContainedEntity containedIndexedEmbedded) { this.containedIndexedEmbedded = containedIndexedEmbedded; } public ContainedEntity getContainedNonIndexedEmbedded() { return containedNonIndexedEmbedded; } public void setContainedNonIndexedEmbedded(ContainedEntity containedNonIndexedEmbedded) { this.containedNonIndexedEmbedded = containedNonIndexedEmbedded; } public ContainedEntity getContainedIndexedEmbeddedShallowReindexOnUpdate() { return containedIndexedEmbeddedShallowReindexOnUpdate; } public void setContainedIndexedEmbeddedShallowReindexOnUpdate( ContainedEntity containedIndexedEmbeddedShallowReindexOnUpdate) { this.containedIndexedEmbeddedShallowReindexOnUpdate = containedIndexedEmbeddedShallowReindexOnUpdate; } public ContainedEntity getContainedIndexedEmbeddedNoReindexOnUpdate() { return containedIndexedEmbeddedNoReindexOnUpdate; } public void setContainedIndexedEmbeddedNoReindexOnUpdate( ContainedEntity containedIndexedEmbeddedNoReindexOnUpdate) { this.containedIndexedEmbeddedNoReindexOnUpdate = containedIndexedEmbeddedNoReindexOnUpdate; } public ContainedEntity getContainedUsedInCrossEntityDerivedProperty() { return containedUsedInCrossEntityDerivedProperty; } public void setContainedUsedInCrossEntityDerivedProperty( ContainedEntity containedUsedInCrossEntityDerivedProperty) { this.containedUsedInCrossEntityDerivedProperty = containedUsedInCrossEntityDerivedProperty; } public Object getContainedIndexedEmbeddedWithCast() { return containedIndexedEmbeddedWithCast; } public void setContainedIndexedEmbeddedWithCast(Object containedIndexedEmbeddedWithCast) { this.containedIndexedEmbeddedWithCast = containedIndexedEmbeddedWithCast; } public ContainingEmbeddable getEmbeddedAssociations() { return embeddedAssociations; } public void setEmbeddedAssociations(ContainingEmbeddable embeddedAssociations) { this.embeddedAssociations = embeddedAssociations; } public ContainedEntity getContainedElementCollectionAssociationsIndexedEmbedded() { return containedElementCollectionAssociationsIndexedEmbedded; } public void setContainedElementCollectionAssociationsIndexedEmbedded( ContainedEntity containedElementCollectionAssociationsIndexedEmbedded) { this.containedElementCollectionAssociationsIndexedEmbedded = containedElementCollectionAssociationsIndexedEmbedded; } public ContainedEntity getContainedElementCollectionAssociationsNonIndexedEmbedded() { return containedElementCollectionAssociationsNonIndexedEmbedded; } public void setContainedElementCollectionAssociationsNonIndexedEmbedded( ContainedEntity containedElementCollectionAssociationsNonIndexedEmbedded) { this.containedElementCollectionAssociationsNonIndexedEmbedded = containedElementCollectionAssociationsNonIndexedEmbedded; } @Transient @GenericField @IndexingDependency(derivedFrom = { @ObjectPath({ @PropertyValue(propertyName = "containedUsedInCrossEntityDerivedProperty"), @PropertyValue(propertyName = "fieldUsedInCrossEntityDerivedField1") }), @ObjectPath({ @PropertyValue(propertyName = "containedUsedInCrossEntityDerivedProperty"), @PropertyValue(propertyName = "fieldUsedInCrossEntityDerivedField2") }) }) public Optional<String> getCrossEntityDerivedField() { return containedUsedInCrossEntityDerivedProperty == null ? Optional.empty() : computeDerived( Stream.of( containedUsedInCrossEntityDerivedProperty.getFieldUsedInCrossEntityDerivedField1(), containedUsedInCrossEntityDerivedProperty.getFieldUsedInCrossEntityDerivedField2() ) ); } static final ContainingEntityPrimitives<ContainingEntity, ContainingEmbeddable, ContainedEntity> PRIMITIVES = new ContainingEntityPrimitives<ContainingEntity, ContainingEmbeddable, ContainedEntity>() { @Override public Class<ContainingEntity> entityClass() { return ContainingEntity.class; } @Override public ContainingEntity newInstance(int id) { ContainingEntity entity = new ContainingEntity(); entity.setId( id ); return entity; } @Override public PropertyAccessor<ContainingEntity, ContainingEntity> child() { return PropertyAccessor.create( ContainingEntity::setChild ); } @Override public PropertyAccessor<ContainingEntity, ContainingEntity> parent() { return PropertyAccessor.create( ContainingEntity::setParent ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedIndexedEmbedded() { return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbedded, ContainingEntity::getContainedIndexedEmbedded ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedNonIndexedEmbedded() { return PropertyAccessor.create( ContainingEntity::setContainedNonIndexedEmbedded, ContainingEntity::getContainedNonIndexedEmbedded ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedIndexedEmbeddedShallowReindexOnUpdate() { return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbeddedShallowReindexOnUpdate, ContainingEntity::getContainedIndexedEmbeddedShallowReindexOnUpdate ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedIndexedEmbeddedNoReindexOnUpdate() { return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbeddedNoReindexOnUpdate, ContainingEntity::getContainedIndexedEmbeddedNoReindexOnUpdate ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedUsedInCrossEntityDerivedProperty() { return PropertyAccessor.create( ContainingEntity::setContainedUsedInCrossEntityDerivedProperty, ContainingEntity::getContainedUsedInCrossEntityDerivedProperty ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedIndexedEmbeddedWithCast() { return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbeddedWithCast ); } @Override public PropertyAccessor<ContainingEntity, ContainingEmbeddable> embeddedAssociations() { return PropertyAccessor.create( ContainingEntity::setEmbeddedAssociations, ContainingEntity::getEmbeddedAssociations ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedElementCollectionAssociationsIndexedEmbedded() { return PropertyAccessor.create( ContainingEntity::setContainedElementCollectionAssociationsIndexedEmbedded, ContainingEntity::getContainedElementCollectionAssociationsIndexedEmbedded ); } @Override public PropertyAccessor<ContainingEntity, ContainedEntity> containedElementCollectionAssociationsNonIndexedEmbedded() { return PropertyAccessor.create( ContainingEntity::setContainedElementCollectionAssociationsNonIndexedEmbedded, ContainingEntity::getContainedElementCollectionAssociationsNonIndexedEmbedded ); } @Override public PropertyAccessor<ContainingEntity, String> nonIndexedField() { return PropertyAccessor.create( ContainingEntity::setNonIndexedField ); } }; } public static class ContainingEmbeddable { @OneToOne(mappedBy = "embeddedAssociations.containingAsIndexedEmbedded") @IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" }, name = "containedIndexedEmbedded") private ContainedEntity containedIndexedEmbedded; @OneToOne(mappedBy = "embeddedAssociations.containingAsNonIndexedEmbedded") private ContainedEntity containedNonIndexedEmbedded; public ContainedEntity getContainedIndexedEmbedded() { return containedIndexedEmbedded; } public void setContainedIndexedEmbedded(ContainedEntity containedIndexedEmbedded) { this.containedIndexedEmbedded = containedIndexedEmbedded; } public ContainedEntity getContainedNonIndexedEmbedded() { return containedNonIndexedEmbedded; } public void setContainedNonIndexedEmbedded(ContainedEntity containedNonIndexedEmbedded) { this.containedNonIndexedEmbedded = containedNonIndexedEmbedded; } static final ContainingEmbeddablePrimitives<ContainingEmbeddable, ContainedEntity> PRIMITIVES = new ContainingEmbeddablePrimitives<ContainingEmbeddable, ContainedEntity>() { @Override public ContainingEmbeddable newInstance() { return new ContainingEmbeddable(); } @Override public PropertyAccessor<ContainingEmbeddable, ContainedEntity> containedIndexedEmbedded() { return PropertyAccessor.create( ContainingEmbeddable::setContainedIndexedEmbedded, ContainingEmbeddable::getContainedIndexedEmbedded ); } @Override public PropertyAccessor<ContainingEmbeddable, ContainedEntity> containedNonIndexedEmbedded() { return PropertyAccessor.create( ContainingEmbeddable::setContainedNonIndexedEmbedded, ContainingEmbeddable::getContainedNonIndexedEmbedded ); } }; } @Entity(name = "indexed") @Indexed(index = IndexedEntity.INDEX) public static class IndexedEntity extends ContainingEntity { static final String INDEX = "IndexedEntity"; static final IndexedEntityPrimitives<IndexedEntity> PRIMITIVES = new IndexedEntityPrimitives<IndexedEntity>() { @Override public Class<IndexedEntity> entityClass() { return IndexedEntity.class; } @Override public String indexName() { return IndexedEntity.INDEX; } @Override public IndexedEntity newInstance(int id) { IndexedEntity entity = new IndexedEntity(); entity.setId( id ); return entity; } }; } @Entity(name = "contained") public static class ContainedEntity { @Id private Integer id; @OneToOne(fetch = FetchType.LAZY) @LazyGroup("containingAsIndexedEmbedded") @JoinColumn(name = "CIndexedEmbedded") private ContainingEntity containingAsIndexedEmbedded; @OneToOne(fetch = FetchType.LAZY) @LazyGroup("containingAsNonIndexedEmbedded") @JoinColumn(name = "CNonIndexedEmbedded") private ContainingEntity containingAsNonIndexedEmbedded; @OneToOne(fetch = FetchType.LAZY) @LazyGroup("containingAsIndexedEmbeddedShallowReindexOnUpdate") @JoinColumn(name = "CIndexedEmbeddedSROU") private ContainingEntity containingAsIndexedEmbeddedShallowReindexOnUpdate; @OneToOne(fetch = FetchType.LAZY) @LazyGroup("containingAsIndexedEmbeddedNoReindexOnUpdate") @JoinColumn(name = "CIndexedEmbeddedNROU") private ContainingEntity containingAsIndexedEmbeddedNoReindexOnUpdate; @OneToOne(fetch = FetchType.LAZY) @LazyGroup("containingAsUsedInCrossEntityDerivedProperty") @JoinColumn(name = "CCrossEntityDerived") private ContainingEntity containingAsUsedInCrossEntityDerivedProperty; @OneToOne(targetEntity = ContainingEntity.class, fetch = FetchType.LAZY) @LazyGroup("containingAsIndexedEmbeddedWithCast") @JoinColumn(name = "CIndexedEmbeddedCast") private Object containingAsIndexedEmbeddedWithCast; @Embedded private ContainedEmbeddable embeddedAssociations; @ElementCollection @LazyGroup("elementCollectionAssociations") @Embedded @OrderColumn(name = "idx") @CollectionTable(name = "c_ECAssoc") private List<ContainedEmbeddable> elementCollectionAssociations = new ArrayList<>(); @Basic @GenericField private String indexedField; @ElementCollection @OrderColumn(name = "idx") @CollectionTable(name = "indexedECF") @GenericField private List<String> indexedElementCollectionField = new ArrayList<>(); @Basic @GenericField // Keep this annotation, it should be ignored because the field is not included in the @IndexedEmbedded private String nonIndexedField; @ElementCollection @OrderColumn(name = "idx") @CollectionTable(name = "nonIndexedECF") @Column(name = "nonIndexedECF") @GenericField // Keep this annotation, it should be ignored because the field is not included in the @IndexedEmbedded private List<String> nonIndexedElementCollectionField = new ArrayList<>(); @Basic // Do not annotate with @GenericField, this would make the test pointless @Column(name = "FUIContainedDF1") private String fieldUsedInContainedDerivedField1; @Basic // Do not annotate with @GenericField, this would make the test pointless @Column(name = "FUIContainedDF2") private String fieldUsedInContainedDerivedField2; @Basic // Do not annotate with @GenericField, this would make the test pointless @Column(name = "FUICrossEntityDF1") private String fieldUsedInCrossEntityDerivedField1; @Basic // Do not annotate with @GenericField, this would make the test pointless @Column(name = "FUICrossEntityDF2") private String fieldUsedInCrossEntityDerivedField2; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public ContainingEntity getContainingAsIndexedEmbedded() { return containingAsIndexedEmbedded; } public void setContainingAsIndexedEmbedded(ContainingEntity containingAsIndexedEmbedded) { this.containingAsIndexedEmbedded = containingAsIndexedEmbedded; } public ContainingEntity getContainingAsNonIndexedEmbedded() { return containingAsNonIndexedEmbedded; } public void setContainingAsNonIndexedEmbedded(ContainingEntity containingAsNonIndexedEmbedded) { this.containingAsNonIndexedEmbedded = containingAsNonIndexedEmbedded; } public ContainingEntity getContainingAsIndexedEmbeddedShallowReindexOnUpdate() { return containingAsIndexedEmbeddedShallowReindexOnUpdate; } public void setContainingAsIndexedEmbeddedShallowReindexOnUpdate( ContainingEntity containingAsIndexedEmbeddedShallowReindexOnUpdate) { this.containingAsIndexedEmbeddedShallowReindexOnUpdate = containingAsIndexedEmbeddedShallowReindexOnUpdate; } public ContainingEntity getContainingAsIndexedEmbeddedNoReindexOnUpdate() { return containingAsIndexedEmbeddedNoReindexOnUpdate; } public void setContainingAsIndexedEmbeddedNoReindexOnUpdate( ContainingEntity containingAsIndexedEmbeddedNoReindexOnUpdate) { this.containingAsIndexedEmbeddedNoReindexOnUpdate = containingAsIndexedEmbeddedNoReindexOnUpdate; } public ContainingEntity getContainingAsUsedInCrossEntityDerivedProperty() { return containingAsUsedInCrossEntityDerivedProperty; } public void setContainingAsUsedInCrossEntityDerivedProperty( ContainingEntity containingAsUsedInCrossEntityDerivedProperty) { this.containingAsUsedInCrossEntityDerivedProperty = containingAsUsedInCrossEntityDerivedProperty; } public Object getContainingAsIndexedEmbeddedWithCast() { return containingAsIndexedEmbeddedWithCast; } public void setContainingAsIndexedEmbeddedWithCast(Object containingAsIndexedEmbeddedWithCast) { this.containingAsIndexedEmbeddedWithCast = containingAsIndexedEmbeddedWithCast; } public ContainedEmbeddable getEmbeddedAssociations() { return embeddedAssociations; } public void setEmbeddedAssociations(ContainedEmbeddable embeddedAssociations) { this.embeddedAssociations = embeddedAssociations; } public List<ContainedEmbeddable> getElementCollectionAssociations() { return elementCollectionAssociations; } public String getIndexedField() { return indexedField; } public void setIndexedField(String indexedField) { this.indexedField = indexedField; } public List<String> getIndexedElementCollectionField() { return indexedElementCollectionField; } public void setIndexedElementCollectionField(List<String> indexedElementCollectionField) { this.indexedElementCollectionField = indexedElementCollectionField; } public String getNonIndexedField() { return nonIndexedField; } public void setNonIndexedField(String nonIndexedField) { this.nonIndexedField = nonIndexedField; } public List<String> getNonIndexedElementCollectionField() { return nonIndexedElementCollectionField; } public void setNonIndexedElementCollectionField(List<String> nonIndexedElementCollectionField) { this.nonIndexedElementCollectionField = nonIndexedElementCollectionField; } public String getFieldUsedInContainedDerivedField1() { return fieldUsedInContainedDerivedField1; } public void setFieldUsedInContainedDerivedField1(String fieldUsedInContainedDerivedField1) { this.fieldUsedInContainedDerivedField1 = fieldUsedInContainedDerivedField1; } public String getFieldUsedInContainedDerivedField2() { return fieldUsedInContainedDerivedField2; } public void setFieldUsedInContainedDerivedField2(String fieldUsedInContainedDerivedField2) { this.fieldUsedInContainedDerivedField2 = fieldUsedInContainedDerivedField2; } public String getFieldUsedInCrossEntityDerivedField1() { return fieldUsedInCrossEntityDerivedField1; } public void setFieldUsedInCrossEntityDerivedField1(String fieldUsedInCrossEntityDerivedField1) { this.fieldUsedInCrossEntityDerivedField1 = fieldUsedInCrossEntityDerivedField1; } public String getFieldUsedInCrossEntityDerivedField2() { return fieldUsedInCrossEntityDerivedField2; } public void setFieldUsedInCrossEntityDerivedField2(String fieldUsedInCrossEntityDerivedField2) { this.fieldUsedInCrossEntityDerivedField2 = fieldUsedInCrossEntityDerivedField2; } @Transient @GenericField @IndexingDependency(derivedFrom = { @ObjectPath(@PropertyValue(propertyName = "fieldUsedInContainedDerivedField1")), @ObjectPath(@PropertyValue(propertyName = "fieldUsedInContainedDerivedField2")) }) public Optional<String> getContainedDerivedField() { return computeDerived( Stream.of( fieldUsedInContainedDerivedField1, fieldUsedInContainedDerivedField2 ) ); } static ContainedEntityPrimitives<ContainedEntity, ContainedEmbeddable, ContainingEntity> PRIMITIVES = new ContainedEntityPrimitives<ContainedEntity, ContainedEmbeddable, ContainingEntity>() { @Override public Class<ContainedEntity> entityClass() { return ContainedEntity.class; } @Override public ContainedEntity newInstance(int id) { ContainedEntity entity = new ContainedEntity(); entity.setId( id ); return entity; } @Override public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsIndexedEmbedded() { return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbedded, ContainedEntity::getContainingAsIndexedEmbedded ); } @Override public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsNonIndexedEmbedded() { return PropertyAccessor.create( ContainedEntity::setContainingAsNonIndexedEmbedded, ContainedEntity::getContainingAsNonIndexedEmbedded ); } @Override public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsIndexedEmbeddedShallowReindexOnUpdate() { return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbeddedShallowReindexOnUpdate, ContainedEntity::getContainingAsIndexedEmbeddedShallowReindexOnUpdate ); } @Override public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsIndexedEmbeddedNoReindexOnUpdate() { return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbeddedNoReindexOnUpdate, ContainedEntity::getContainingAsIndexedEmbeddedNoReindexOnUpdate ); } @Override public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsUsedInCrossEntityDerivedProperty() { return PropertyAccessor.create( ContainedEntity::setContainingAsUsedInCrossEntityDerivedProperty, ContainedEntity::getContainingAsUsedInCrossEntityDerivedProperty ); } @Override public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsIndexedEmbeddedWithCast() { return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbeddedWithCast ); } @Override public PropertyAccessor<ContainedEntity, ContainedEmbeddable> embeddedAssociations() { return PropertyAccessor.create( ContainedEntity::setEmbeddedAssociations, ContainedEntity::getEmbeddedAssociations ); } @Override public MultiValuedPropertyAccessor<ContainedEntity, ContainedEmbeddable, List<ContainedEmbeddable>> elementCollectionAssociations() { return MultiValuedPropertyAccessor.create( ContainerPrimitives.collection(), ContainedEntity::getElementCollectionAssociations ); } @Override public PropertyAccessor<ContainedEntity, String> indexedField() { return PropertyAccessor.create( ContainedEntity::setIndexedField ); } @Override public PropertyAccessor<ContainedEntity, String> nonIndexedField() { return PropertyAccessor.create( ContainedEntity::setNonIndexedField ); } @Override public MultiValuedPropertyAccessor<ContainedEntity, String, List<String>> indexedElementCollectionField() { return MultiValuedPropertyAccessor.create( ContainerPrimitives.collection(), ContainedEntity::getIndexedElementCollectionField, ContainedEntity::setIndexedElementCollectionField ); } @Override public MultiValuedPropertyAccessor<ContainedEntity, String, List<String>> nonIndexedElementCollectionField() { return MultiValuedPropertyAccessor.create( ContainerPrimitives.collection(), ContainedEntity::getNonIndexedElementCollectionField, ContainedEntity::setNonIndexedElementCollectionField ); } @Override public PropertyAccessor<ContainedEntity, String> fieldUsedInContainedDerivedField1() { return PropertyAccessor.create( ContainedEntity::setFieldUsedInContainedDerivedField1 ); } @Override public PropertyAccessor<ContainedEntity, String> fieldUsedInContainedDerivedField2() { return PropertyAccessor.create( ContainedEntity::setFieldUsedInContainedDerivedField2 ); } @Override public PropertyAccessor<ContainedEntity, String> fieldUsedInCrossEntityDerivedField1() { return PropertyAccessor.create( ContainedEntity::setFieldUsedInCrossEntityDerivedField1 ); } @Override public PropertyAccessor<ContainedEntity, String> fieldUsedInCrossEntityDerivedField2() { return PropertyAccessor.create( ContainedEntity::setFieldUsedInCrossEntityDerivedField2 ); } }; } public static class ContainedEmbeddable { @OneToOne(fetch = FetchType.LAZY) @LazyGroup("embeddable_containingAsIndexedEmbedded") @JoinColumn(name = "CEmbIdxEmbedded") private ContainingEntity containingAsIndexedEmbedded; @OneToOne(fetch = FetchType.LAZY) @LazyGroup("embeddable_containingAsNonIndexedEmbedded") @JoinColumn(name = "CEmbNonIdxEmbedded") private ContainingEntity containingAsNonIndexedEmbedded; public ContainingEntity getContainingAsIndexedEmbedded() { return containingAsIndexedEmbedded; } public void setContainingAsIndexedEmbedded(ContainingEntity containingAsIndexedEmbedded) { this.containingAsIndexedEmbedded = containingAsIndexedEmbedded; } public ContainingEntity getContainingAsNonIndexedEmbedded() { return containingAsNonIndexedEmbedded; } public void setContainingAsNonIndexedEmbedded(ContainingEntity containingAsNonIndexedEmbedded) { this.containingAsNonIndexedEmbedded = containingAsNonIndexedEmbedded; } static ContainedEmbeddablePrimitives<ContainedEmbeddable, ContainingEntity> PRIMITIVES = new ContainedEmbeddablePrimitives<ContainedEmbeddable, ContainingEntity>() { @Override public ContainedEmbeddable newInstance() { return new ContainedEmbeddable(); } @Override public PropertyAccessor<ContainedEmbeddable, ContainingEntity> containingAsIndexedEmbedded() { return PropertyAccessor.create( ContainedEmbeddable::setContainingAsIndexedEmbedded, ContainedEmbeddable::getContainingAsIndexedEmbedded ); } @Override public PropertyAccessor<ContainedEmbeddable, ContainingEntity> containingAsNonIndexedEmbedded() { return PropertyAccessor.create( ContainedEmbeddable::setContainingAsNonIndexedEmbedded, ContainedEmbeddable::getContainingAsNonIndexedEmbedded ); } }; } }