idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
2,200
public static Map < String , Object > get ( File packageFile ) throws IOException { ZipFile zipFile = null ; try { zipFile = new ZipFile ( packageFile ) ; ZipArchiveEntry entry = zipFile . getEntry ( ZIP_ENTRY_PROPERTIES ) ; if ( entry != null && ! entry . isDirectory ( ) ) { Map < String , Object > props = getPackageProperties ( zipFile , entry ) ; return new TreeMap < > ( transformPropertyTypes ( props ) ) ; } return Collections . emptyMap ( ) ; } finally { IOUtils . closeQuietly ( zipFile ) ; } }
Get properties of AEM package .
2,201
private static Object transformType ( Object value ) { if ( value == null ) { return null ; } String valueString = value . toString ( ) ; boolean boolValue = BooleanUtils . toBoolean ( valueString ) ; if ( StringUtils . equals ( valueString , Boolean . toString ( boolValue ) ) ) { return boolValue ; } int intValue = NumberUtils . toInt ( valueString ) ; if ( StringUtils . equals ( valueString , Integer . toString ( intValue ) ) ) { return intValue ; } return value ; }
Detects if string values are boolean or integer and transforms them to correct types .
2,202
public static RequestConfig buildRequestConfig ( PackageManagerProperties props ) { return RequestConfig . custom ( ) . setConnectTimeout ( props . getHttpConnectTimeoutSec ( ) * ( int ) DateUtils . MILLIS_PER_SECOND ) . setSocketTimeout ( props . getHttpSocketTimeoutSec ( ) * ( int ) DateUtils . MILLIS_PER_SECOND ) . build ( ) ; }
Built custom request configuration from package manager properties .
2,203
public static void applyRequestConfig ( HttpRequestBase httpRequest , PackageFile packageFile , PackageManagerProperties props ) { Integer httpSocketTimeoutSec = packageFile . getHttpSocketTimeoutSec ( ) ; if ( httpSocketTimeoutSec == null ) { return ; } RequestConfig defaultConfig = buildRequestConfig ( props ) ; httpRequest . setConfig ( RequestConfig . copy ( defaultConfig ) . setSocketTimeout ( httpSocketTimeoutSec * ( int ) DateUtils . MILLIS_PER_SECOND ) . build ( ) ) ; }
Apply timeout configurations that are defined specific for this package file .
2,204
private static int headingIndex ( Element element ) { String tagName = element . tagName ( ) ; if ( tagName . startsWith ( "h" ) ) { try { return Integer . parseInt ( tagName . substring ( 1 ) ) ; } catch ( Throwable ex ) { throw new IllegalArgumentException ( "Must be a header tag: " + tagName , ex ) ; } } else { throw new IllegalArgumentException ( "Must be a header tag: " + tagName ) ; } }
Retrieves numeric index of a heading .
2,205
private boolean isI18nSourceFileChanged ( File sourceDirectory ) { Scanner scanner = buildContext . newScanner ( sourceDirectory ) ; Scanner deleteScanner = buildContext . newDeleteScanner ( sourceDirectory ) ; return isI18nSourceFileChanged ( scanner ) || isI18nSourceFileChanged ( deleteScanner ) ; }
Checks if and i18n source file was changes in incremental build .
2,206
private void intialize ( File sourceDirectory ) throws IOException { getLog ( ) . debug ( "Initializing i18n plugin..." ) ; if ( ! getI18nSourceFiles ( sourceDirectory ) . isEmpty ( ) ) { File myGeneratedResourcesFolder = getGeneratedResourcesFolder ( ) ; addResource ( myGeneratedResourcesFolder . getPath ( ) , target ) ; } }
Initialize parameters which cannot get defaults from annotations . Currently only the root nodes .
2,207
@ SuppressWarnings ( "unchecked" ) private List < File > getI18nSourceFiles ( File sourceDirectory ) throws IOException { if ( i18nSourceFiles == null ) { if ( ! sourceDirectory . isDirectory ( ) ) { i18nSourceFiles = Collections . emptyList ( ) ; } else { String includes = StringUtils . join ( SOURCE_FILES_INCLUDES , "," ) ; String excludes = FileUtils . getDefaultExcludesAsString ( ) ; i18nSourceFiles = FileUtils . getFiles ( sourceDirectory , includes , excludes ) ; } } return i18nSourceFiles ; }
Fetches i18n source files from source directory .
2,208
private File getSourceDirectory ( ) throws IOException { File file = new File ( source ) ; if ( ! file . isDirectory ( ) ) { getLog ( ) . debug ( "Could not find directory at '" + source + "'" ) ; } return file . getCanonicalFile ( ) ; }
Get directory containing source i18n files .
2,209
private void writeTargetI18nFile ( SlingI18nMap i18nMap , File targetfile , OutputFormat selectedOutputFormat ) throws IOException , JSONException { if ( selectedOutputFormat == OutputFormat . XML ) { FileUtils . fileWrite ( targetfile , CharEncoding . UTF_8 , i18nMap . getI18nXmlString ( ) ) ; } else if ( selectedOutputFormat == OutputFormat . PROPERTIES ) { FileUtils . fileWrite ( targetfile , CharEncoding . ISO_8859_1 , i18nMap . getI18nPropertiesString ( ) ) ; } else { FileUtils . fileWrite ( targetfile , CharEncoding . UTF_8 , i18nMap . getI18nJsonString ( ) ) ; } buildContext . refresh ( targetfile ) ; }
Writes mappings to file in Sling compatible JSON format .
2,210
private File getTargetFile ( File sourceFile , OutputFormat selectedOutputFormat ) throws IOException { File sourceDirectory = getSourceDirectory ( ) ; String relativePath = StringUtils . substringAfter ( sourceFile . getAbsolutePath ( ) , sourceDirectory . getAbsolutePath ( ) ) ; String relativeTargetPath = FileUtils . removeExtension ( relativePath ) + "." + selectedOutputFormat . getFileExtension ( ) ; File jsonFile = new File ( getGeneratedResourcesFolder ( ) . getPath ( ) + relativeTargetPath ) ; jsonFile = jsonFile . getCanonicalFile ( ) ; File parentDirectory = jsonFile . getParentFile ( ) ; if ( ! parentDirectory . exists ( ) ) { parentDirectory . mkdirs ( ) ; buildContext . refresh ( parentDirectory ) ; } return jsonFile ; }
Get the JSON file for source file .
2,211
private I18nReader getI18nReader ( File sourceFile ) throws MojoFailureException { String extension = FileUtils . getExtension ( sourceFile . getName ( ) ) ; if ( StringUtils . equalsIgnoreCase ( extension , FILE_EXTENSION_PROPERTIES ) ) { return new PropertiesI18nReader ( ) ; } if ( StringUtils . equalsIgnoreCase ( extension , FILE_EXTENSION_XML ) ) { return new XmlI18nReader ( ) ; } if ( StringUtils . equalsIgnoreCase ( extension , FILE_EXTENSION_JSON ) ) { return new JsonI18nReader ( ) ; } throw new MojoFailureException ( "Unsupported file extension '" + extension + "': " + sourceFile . getAbsolutePath ( ) ) ; }
Get i18n reader for source file .
2,212
public List < CompletionItem > resolve ( String filter , int startOffset , int caretOffset ) { final Set < ElementHandle < TypeElement > > result = classpath . getClassIndex ( ) . getDeclaredTypes ( "" , ClassIndex . NameKind . PREFIX , EnumSet . of ( ClassIndex . SearchScope . SOURCE ) ) ; List < CompletionItem > ret = new ArrayList < > ( ) ; for ( ElementHandle < TypeElement > te : result ) { if ( te . getKind ( ) . isClass ( ) ) { String binaryName = te . getBinaryName ( ) ; if ( ! StringUtils . equals ( binaryName , "" ) && StringUtils . startsWith ( binaryName , filter ) ) { ret . add ( new BasicCompletionItem ( te . getBinaryName ( ) , false , startOffset , caretOffset ) ) ; } } } return ret ; }
returns a list with all classes matchting the given filter
2,213
public ContentPackageBuilder property ( String property , Object value ) { metadata . addProperty ( property , value ) ; return this ; }
Add custom package metadata property .
2,214
public ContentPackageBuilder xmlNamespace ( String prefix , String uri ) { metadata . addXmlNamespace ( prefix , uri ) ; return this ; }
Register a XML namespace that is used by your content added to the JCR XML . This method can be called multiple times to register multiple namespaces . The JCR namespaces jcr nt cq and sling are registered by default .
2,215
public ContentPackageBuilder thumbnailImage ( InputStream is ) throws IOException { metadata . setThumbnailImage ( IOUtils . toByteArray ( is ) ) ; return this ; }
Set thumbnail PNG image .
2,216
@ SuppressWarnings ( "unchecked" ) public static final Module createModule ( List < JsonSerializer < ? > > serializers , Map < Class < ? > , JsonDeserializer < ? > > deserializers ) { SimpleModule module = new SimpleModule ( ) ; if ( CollectionUtils . isNotEmpty ( serializers ) ) { for ( JsonSerializer < ? > serializer : serializers ) { module . addSerializer ( serializer ) ; } } if ( MapUtils . isNotEmpty ( deserializers ) ) { for ( Map . Entry < Class < ? > , JsonDeserializer < ? > > entry : deserializers . entrySet ( ) ) { Class < Object > type = ( Class < Object > ) entry . getKey ( ) ; JsonDeserializer < Object > des = ( JsonDeserializer < Object > ) entry . getValue ( ) ; module . addDeserializer ( type , des ) ; } } return module ; }
Creates a module from a set of serializers and deserializes .
2,217
public static SecretKey generateKey ( String cipherAlgorithm ) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator . getInstance ( cipherAlgorithm ) ; keyGenerator . init ( secureRandom ) ; return keyGenerator . generateKey ( ) ; }
Generates a random encryption key .
2,218
public static boolean matchPassword ( String hashedPswdAndSalt , String clearPswd ) { if ( StringUtils . isNotEmpty ( hashedPswdAndSalt ) && StringUtils . isNotEmpty ( clearPswd ) ) { int idxOfSep = hashedPswdAndSalt . indexOf ( PASSWORD_SEP ) ; String storedHash = hashedPswdAndSalt . substring ( 0 , idxOfSep ) ; String salt = hashedPswdAndSalt . substring ( idxOfSep + 1 ) ; SimpleDigest digest = new SimpleDigest ( ) ; digest . setBase64Salt ( salt ) ; return storedHash . equals ( digest . digestBase64 ( clearPswd ) ) ; } else if ( hashedPswdAndSalt == null && clearPswd == null ) { return true ; } else if ( hashedPswdAndSalt . isEmpty ( ) && clearPswd . isEmpty ( ) ) { return true ; } else { return false ; } }
Returns true if it s a password match that is if the hashed clear password equals the given hash .
2,219
public static < T > List < T > toList ( Iterable < T > iterable ) { List < T > list = null ; if ( iterable != null ) { list = new ArrayList < > ( ) ; for ( T elem : iterable ) { list . add ( elem ) ; } } return list ; }
Creates a new list from the iterable elements .
2,220
public static < T > int count ( Iterable < T > iterable ) { int count = 0 ; if ( iterable != null ) { Iterator < T > iter = iterable . iterator ( ) ; while ( iter . hasNext ( ) ) { iter . next ( ) ; count ++ ; } } return count ; }
Returns the number of elements the iterable contains .
2,221
public static StringBuilder getBaseRequestUrl ( HttpServletRequest request , boolean forceHttps ) { String scheme = forceHttps ? HTTPS_SCHEME : request . getScheme ( ) ; String serverName = request . getServerName ( ) ; int serverPort = request . getServerPort ( ) ; StringBuilder url = new StringBuilder ( ) ; url . append ( scheme ) . append ( "://" ) . append ( serverName ) ; if ( ! ( scheme . equals ( HTTP_SCHEME ) && serverPort == DEFAULT_HTTP_PORT ) && ! ( scheme . equals ( HTTPS_SCHEME ) && serverPort == DEFAULT_HTTPS_PORT ) ) { url . append ( ":" ) . append ( serverPort ) ; } return url ; }
Returns the portion from the URL that includes the scheme server name and port number without the server path .
2,222
public static String getFullUrl ( HttpServletRequest request , String relativeUrl ) { StringBuilder baseUrl = getBaseRequestUrl ( request , false ) ; String contextPath = request . getContextPath ( ) ; String servletPath = request . getServletPath ( ) ; if ( contextPath . equals ( "/" ) ) { contextPath = "" ; } if ( servletPath . equals ( "/" ) ) { servletPath = "" ; } return baseUrl . append ( contextPath ) . append ( servletPath ) . append ( relativeUrl ) . toString ( ) ; }
Returns the full URL for the relative URL based in the specified request . The full URL includes the scheme server name port number context path and server path .
2,223
public static final String getRequestUriWithoutContextPath ( HttpServletRequest request ) { String uri = request . getRequestURI ( ) . substring ( request . getContextPath ( ) . length ( ) ) ; if ( ! uri . isEmpty ( ) ) { return uri ; } else { return "/" ; } }
Returns the request URI without the context path .
2,224
public static final String getFullRequestUri ( HttpServletRequest request , boolean includeQueryString ) { StringBuilder uri = getBaseRequestUrl ( request , false ) . append ( request . getRequestURI ( ) ) ; if ( includeQueryString ) { String queryStr = request . getQueryString ( ) ; if ( StringUtils . isNotEmpty ( queryStr ) ) { uri . append ( '?' ) . append ( queryStr ) ; } } return uri . toString ( ) ; }
Returns the full request URI including scheme server name port number and server path . The query string is optional .
2,225
public static Cookie getCookie ( String name , HttpServletRequest request ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( ArrayUtils . isNotEmpty ( cookies ) ) { for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( name ) ) { return cookie ; } } } return null ; }
Returns the cookie with the given name for the given request
2,226
public static String getCookieValue ( String name , HttpServletRequest request ) { Cookie cookie = getCookie ( name , request ) ; if ( cookie != null ) { return cookie . getValue ( ) ; } else { return null ; } }
Returns the cookie value with the given name for the given request
2,227
public static void addValue ( String key , Object value , MultiValueMap < String , String > params ) { if ( value != null ) { params . add ( key , value . toString ( ) ) ; } }
Adds a param value to a params map . If value is null nothing is done .
2,228
public static void addValues ( String key , Collection < String > values , MultiValueMap < String , String > params ) { if ( values != null ) { for ( String value : values ) { params . add ( key , value ) ; } } }
Adds a collection of param values to a params map . If the collection is null nothing is done .
2,229
@ SuppressWarnings ( "unchecked" ) public static MultiValueMap < String , String > getParamsFromQueryString ( String queryString ) { MultiValueMap queryParams = new LinkedMultiValueMap < > ( ) ; if ( StringUtils . isNotEmpty ( queryString ) ) { String [ ] params = queryString . split ( "&" ) ; for ( String param : params ) { String [ ] splitParam = param . split ( "=" ) ; String paramName = splitParam [ 0 ] ; String paramValue = splitParam [ 1 ] ; queryParams . add ( paramName , paramValue ) ; } } return queryParams ; }
Returns a map with the extracted parameters from the specified query string . A multi value map is used since there can be several values for the same param .
2,230
public static Map < String , Object > createRequestParamsMap ( HttpServletRequest request ) { Map < String , Object > paramsMap = new HashMap < > ( ) ; for ( Enumeration paramNameEnum = request . getParameterNames ( ) ; paramNameEnum . hasMoreElements ( ) ; ) { String paramName = ( String ) paramNameEnum . nextElement ( ) ; String [ ] paramValues = request . getParameterValues ( paramName ) ; if ( paramValues . length == 1 ) { paramsMap . put ( paramName , paramValues [ 0 ] ) ; } else { paramsMap . put ( paramName , paramValues ) ; } } return paramsMap ; }
Creates a map from the parameters in the specified request . Multi value parameters will be in an array .
2,231
public static Map < String , Object > createRequestAttributesMap ( HttpServletRequest request ) { Map < String , Object > attributesMap = new HashMap < > ( ) ; for ( Enumeration attributeNameEnum = request . getAttributeNames ( ) ; attributeNameEnum . hasMoreElements ( ) ; ) { String attributeName = ( String ) attributeNameEnum . nextElement ( ) ; attributesMap . put ( attributeName , request . getAttribute ( attributeName ) ) ; } return attributesMap ; }
Creates a map from the request attributes in the specified request .
2,232
public static Map < String , Object > createHeadersMap ( HttpServletRequest request ) { Map < String , Object > headersMap = new HashMap < > ( ) ; for ( Enumeration headerNameEnum = request . getHeaderNames ( ) ; headerNameEnum . hasMoreElements ( ) ; ) { String headerName = ( String ) headerNameEnum . nextElement ( ) ; List < String > headerValues = new ArrayList < String > ( ) ; CollectionUtils . addAll ( headerValues , request . getHeaders ( headerName ) ) ; if ( headerValues . size ( ) == 1 ) { headersMap . put ( headerName , headerValues . get ( 0 ) ) ; } else { headersMap . put ( headerName , headerValues . toArray ( new String [ headerValues . size ( ) ] ) ) ; } } return headersMap ; }
Creates a map from the headers in the specified request . Multi value headers will be in an array .
2,233
public static Map < String , String > createCookiesMap ( HttpServletRequest request ) { Map < String , String > cookiesMap = new HashMap < String , String > ( ) ; Cookie [ ] cookies = request . getCookies ( ) ; if ( ArrayUtils . isNotEmpty ( cookies ) ) { for ( Cookie cookie : request . getCookies ( ) ) { cookiesMap . put ( cookie . getName ( ) , cookie . getValue ( ) ) ; } } return cookiesMap ; }
Creates a map from the cookies in the specified request .
2,234
public static Map < String , Object > createSessionMap ( HttpServletRequest request ) { Map < String , Object > sessionMap = new HashMap < > ( ) ; HttpSession session = request . getSession ( false ) ; if ( session != null ) { for ( Enumeration attributeNameEnum = session . getAttributeNames ( ) ; attributeNameEnum . hasMoreElements ( ) ; ) { String attributeName = ( String ) attributeNameEnum . nextElement ( ) ; sessionMap . put ( attributeName , session . getAttribute ( attributeName ) ) ; } } return sessionMap ; }
Creates a map from the session attributes in the specified request .
2,235
public static void disableCaching ( HttpServletResponse response ) { response . addHeader ( PRAGMA_HEADER_NAME , "no-cache" ) ; response . addHeader ( CACHE_CONTROL_HEADER_NAME , "no-cache, no-store, max-age=0" ) ; response . addDateHeader ( EXPIRES_HEADER_NAME , 1L ) ; }
Disable caching in the client .
2,236
public void addCookie ( String name , String value , HttpServletResponse response ) { Cookie cookie = new Cookie ( name , value ) ; cookie . setHttpOnly ( httpOnly ) ; cookie . setSecure ( secure ) ; if ( StringUtils . isNotEmpty ( domain ) ) { cookie . setDomain ( domain ) ; } if ( StringUtils . isNotEmpty ( path ) ) { cookie . setPath ( path ) ; } if ( maxAge != null ) { cookie . setMaxAge ( maxAge ) ; } response . addCookie ( cookie ) ; logger . debug ( LOG_KEY_ADDED_COOKIE , name ) ; }
Add a new cookie using the configured domain path and max age to the response .
2,237
protected List < MediaType > getAcceptableMediaTypes ( HttpServletRequest request ) throws HttpMediaTypeNotAcceptableException { List < MediaType > mediaTypes = contentNegotiationManager . resolveMediaTypes ( new ServletWebRequest ( request ) ) ; return mediaTypes . isEmpty ( ) ? Collections . singletonList ( MediaType . ALL ) : mediaTypes ; }
Return the acceptable media types from the request .
2,238
protected MediaType getMostSpecificMediaType ( MediaType acceptType , MediaType produceType ) { produceType = produceType . copyQualityValue ( acceptType ) ; return MediaType . SPECIFICITY_COMPARATOR . compare ( acceptType , produceType ) <= 0 ? acceptType : produceType ; }
Return the more specific of the acceptable and the producible media types with the q - value of the former .
2,239
public static void configureNoLogging ( ) { final Logger rootLogger = ( Logger ) LoggerFactory . getLogger ( Logger . ROOT_LOGGER_NAME ) ; final LoggerContext context = rootLogger . getLoggerContext ( ) ; context . reset ( ) ; for ( final Logger logger : context . getLoggerList ( ) ) { if ( logger != rootLogger ) { logger . setLevel ( null ) ; } } rootLogger . setLevel ( OFF ) ; }
Mute all logging .
2,240
public static SentryAppender addSentryAppender ( final String dsn , Level logLevelThreshold ) { final Logger rootLogger = ( Logger ) LoggerFactory . getLogger ( Logger . ROOT_LOGGER_NAME ) ; final LoggerContext context = rootLogger . getLoggerContext ( ) ; SentryAppender appender = new SentryAppender ( ) ; appender . setDsn ( dsn ) ; appender . setContext ( context ) ; ThresholdFilter levelFilter = new ThresholdFilter ( ) ; levelFilter . setLevel ( logLevelThreshold . logbackLevel . toString ( ) ) ; levelFilter . start ( ) ; appender . addFilter ( levelFilter ) ; appender . start ( ) ; rootLogger . addAppender ( appender ) ; return appender ; }
Add a sentry appender .
2,241
private static Appender < ILoggingEvent > getStdErrAppender ( final LoggerContext context , final ReplaceNewLines replaceNewLines ) { final PatternLayoutEncoder encoder = new PatternLayoutEncoder ( ) ; encoder . setContext ( context ) ; encoder . setPattern ( "%date{HH:mm:ss.SSS} %property{ident}[%property{pid}]: %-5level [%thread] %logger{0}: " + ReplaceNewLines . getMsgPattern ( replaceNewLines ) + "%n" ) ; encoder . setCharset ( Charsets . UTF_8 ) ; encoder . start ( ) ; final ConsoleAppender < ILoggingEvent > appender = new ConsoleAppender < ILoggingEvent > ( ) ; appender . setTarget ( "System.err" ) ; appender . setName ( "stderr" ) ; appender . setEncoder ( encoder ) ; appender . setContext ( context ) ; appender . start ( ) ; return appender ; }
Create a stderr appender .
2,242
static Appender < ILoggingEvent > getSyslogAppender ( final LoggerContext context , final String host , final int port , final ReplaceNewLines replaceNewLines ) { final String h = isNullOrEmpty ( host ) ? "localhost" : host ; final int p = port < 0 ? 514 : port ; final MillisecondPrecisionSyslogAppender appender = new MillisecondPrecisionSyslogAppender ( ) ; appender . setFacility ( "LOCAL0" ) ; appender . setSyslogHost ( h ) ; appender . setPort ( p ) ; appender . setName ( "syslog" ) ; appender . setCharset ( Charsets . UTF_8 ) ; appender . setContext ( context ) ; appender . setSuffixPattern ( "%property{ident}[%property{pid}]: " + ReplaceNewLines . getMsgPattern ( replaceNewLines ) ) ; appender . setStackTracePattern ( "%property{ident}[%property{pid}]: " + CoreConstants . TAB ) ; appender . start ( ) ; return appender ; }
Create a syslog appender . The appender will use the facility local0 . If host is null or an empty string default to localhost . If port is less than 0 default to 514 .
2,243
public static void configure ( final File file , final String defaultIdent ) { final Logger rootLogger = ( Logger ) LoggerFactory . getLogger ( Logger . ROOT_LOGGER_NAME ) ; final LoggerContext context = rootLogger . getLoggerContext ( ) ; context . reset ( ) ; UncaughtExceptionLogger . setDefaultUncaughtExceptionHandler ( ) ; try { final JoranConfigurator configurator = new JoranConfigurator ( ) ; configurator . setContext ( context ) ; configurator . doConfigure ( file ) ; } catch ( JoranException je ) { } context . putProperty ( "pid" , getMyPid ( ) ) ; final String hostname = getSpotifyHostname ( ) ; if ( hostname != null ) { context . putProperty ( "hostname" , hostname ) ; } final String ident = context . getProperty ( "ident" ) ; if ( ident == null ) { context . putProperty ( "ident" , defaultIdent ) ; } StatusPrinter . printInCaseOfErrorsOrWarnings ( context ) ; }
Configure logging using a logback configuration file .
2,244
private static String getMyPid ( ) { String pid = "0" ; try { final String nameStr = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; pid = nameStr . split ( "@" ) [ 0 ] ; } catch ( RuntimeException e ) { } return pid ; }
Also the portability of this function is not guaranteed .
2,245
public static void debug ( final Logger logger , final String type , final int version , final Ident ident , final Object ... args ) { logger . debug ( buildLogLine ( type , version , ident , args ) ) ; }
Generate a new debug log message according to the Spotify log format .
2,246
public static < T > Set < T > asSet ( T ... array ) { Set < T > set = null ; if ( array != null ) { set = new HashSet < > ( Arrays . asList ( array ) ) ; } return set ; }
Creates a set from the array elements .
2,247
public static VersionMonitor getVersion ( Class clazz ) throws IOException { Manifest manifest = new Manifest ( ) ; manifest . read ( clazz . getResourceAsStream ( MANIFEST_PATH ) ) ; return getVersion ( manifest ) ; }
Gets the current VersionMonitor base on a Class that will load it s manifest file .
2,248
public static PGPPublicKey getPublicKey ( InputStream content ) throws Exception { InputStream in = PGPUtil . getDecoderStream ( content ) ; PGPPublicKeyRingCollection keyRingCollection = new PGPPublicKeyRingCollection ( in , new BcKeyFingerprintCalculator ( ) ) ; PGPPublicKey key = null ; Iterator < PGPPublicKeyRing > keyRings = keyRingCollection . getKeyRings ( ) ; while ( key == null && keyRings . hasNext ( ) ) { PGPPublicKeyRing keyRing = keyRings . next ( ) ; Iterator < PGPPublicKey > keys = keyRing . getPublicKeys ( ) ; while ( key == null && keys . hasNext ( ) ) { PGPPublicKey current = keys . next ( ) ; if ( current . isEncryptionKey ( ) ) { key = current ; } } } return key ; }
Extracts the PGP public key from an encoded stream .
2,249
public static void encrypt ( Path path , InputStream publicKeyStream , OutputStream targetStream ) throws Exception { PGPPublicKey publicKey = getPublicKey ( publicKeyStream ) ; try ( ByteArrayOutputStream compressed = new ByteArrayOutputStream ( ) ; ArmoredOutputStream armOut = new ArmoredOutputStream ( targetStream ) ) { PGPCompressedDataGenerator compressedGenerator = new PGPCompressedDataGenerator ( PGPCompressedData . ZIP ) ; PGPUtil . writeFileToLiteralData ( compressedGenerator . open ( compressed ) , PGPLiteralData . BINARY , path . toFile ( ) ) ; compressedGenerator . close ( ) ; JcePGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder ( PGPEncryptedData . CAST5 ) . setWithIntegrityPacket ( true ) . setSecureRandom ( new SecureRandom ( ) ) . setProvider ( PROVIDER ) ; PGPEncryptedDataGenerator dataGenerator = new PGPEncryptedDataGenerator ( encryptorBuilder ) ; JcePublicKeyKeyEncryptionMethodGenerator methodGenerator = new JcePublicKeyKeyEncryptionMethodGenerator ( publicKey ) . setProvider ( PROVIDER ) . setSecureRandom ( new SecureRandom ( ) ) ; dataGenerator . addMethod ( methodGenerator ) ; byte [ ] compressedData = compressed . toByteArray ( ) ; OutputStream encryptedOut = dataGenerator . open ( armOut , compressedData . length ) ; encryptedOut . write ( compressedData ) ; encryptedOut . close ( ) ; } }
Performs encryption on a single file using a PGP public key .
2,250
@ SuppressWarnings ( "rawtypes" ) public static void decrypt ( InputStream encryptedStream , OutputStream targetStream , InputStream privateKeyStream , char [ ] password ) throws Exception { BcKeyFingerprintCalculator calculator = new BcKeyFingerprintCalculator ( ) ; PGPObjectFactory factory = new PGPObjectFactory ( PGPUtil . getDecoderStream ( encryptedStream ) , calculator ) ; PGPEncryptedDataList dataList ; Object object = factory . nextObject ( ) ; if ( object instanceof PGPEncryptedDataList ) { dataList = ( PGPEncryptedDataList ) object ; } else { dataList = ( PGPEncryptedDataList ) factory . nextObject ( ) ; } Iterator objects = dataList . getEncryptedDataObjects ( ) ; PGPPrivateKey privateKey = null ; PGPPublicKeyEncryptedData data = null ; while ( privateKey == null && objects . hasNext ( ) ) { data = ( PGPPublicKeyEncryptedData ) objects . next ( ) ; privateKey = findSecretKey ( privateKeyStream , data . getKeyID ( ) , password ) ; } if ( privateKey == null ) { throw new IllegalArgumentException ( "Secret key for message not found." ) ; } decryptData ( privateKey , data , calculator , targetStream ) ; }
Performs decryption of a given stream using a PGP private key .
2,251
protected static PGPPrivateKey findSecretKey ( InputStream keyStream , long keyId , char [ ] password ) throws Exception { PGPSecretKeyRingCollection keyRings = new PGPSecretKeyRingCollection ( PGPUtil . getDecoderStream ( keyStream ) , new BcKeyFingerprintCalculator ( ) ) ; PGPSecretKey secretKey = keyRings . getSecretKey ( keyId ) ; if ( secretKey == null ) { return null ; } PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder ( new JcaPGPDigestCalculatorProviderBuilder ( ) . setProvider ( PROVIDER ) . build ( ) ) . setProvider ( PROVIDER ) . build ( password ) ; return secretKey . extractPrivateKey ( decryptor ) ; }
Extracts the PGP private key from an encoded stream .
2,252
protected static void decryptData ( final PGPPrivateKey privateKey , final PGPPublicKeyEncryptedData data , final BcKeyFingerprintCalculator calculator , final OutputStream targetStream ) throws PGPException , IOException { PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder ( ) . setProvider ( PROVIDER ) . setContentProvider ( PROVIDER ) . build ( privateKey ) ; InputStream content = data . getDataStream ( decryptorFactory ) ; PGPObjectFactory plainFactory = new PGPObjectFactory ( content , calculator ) ; Object message = plainFactory . nextObject ( ) ; if ( message instanceof PGPCompressedData ) { PGPCompressedData compressedData = ( PGPCompressedData ) message ; PGPObjectFactory compressedFactory = new PGPObjectFactory ( compressedData . getDataStream ( ) , calculator ) ; message = compressedFactory . nextObject ( ) ; } if ( message instanceof PGPLiteralData ) { PGPLiteralData literalData = ( PGPLiteralData ) message ; try ( InputStream literalStream = literalData . getInputStream ( ) ) { IOUtils . copy ( literalStream , targetStream ) ; } } else if ( message instanceof PGPOnePassSignatureList ) { throw new PGPException ( "Encrypted message contains a signed message - not literal data." ) ; } else { throw new PGPException ( "Message is not a simple encrypted file - type unknown." ) ; } if ( data . isIntegrityProtected ( ) && ! data . verify ( ) ) { throw new PGPException ( "Message failed integrity check" ) ; } }
Performs the decryption of the given data .
2,253
private OutputStream getSyslogOutputStream ( ) { Field f ; try { f = SyslogAppenderBase . class . getDeclaredField ( "sos" ) ; f . setAccessible ( true ) ; return ( OutputStream ) f . get ( this ) ; } catch ( ReflectiveOperationException e ) { throw Throwables . propagate ( e ) ; } }
Horrible hack to access the syslog stream through reflection
2,254
public static String addParam ( String url , String name , String value , String charset ) throws UnsupportedEncodingException { StringBuilder newUrl = new StringBuilder ( url ) ; if ( ! url . endsWith ( "?" ) && ! url . endsWith ( "&" ) ) { if ( url . contains ( "?" ) ) { newUrl . append ( '&' ) ; } else { newUrl . append ( '?' ) ; } } newUrl . append ( URLEncoder . encode ( name , charset ) ) ; newUrl . append ( '=' ) ; newUrl . append ( URLEncoder . encode ( value , charset ) ) ; return newUrl . toString ( ) ; }
Adds a query string param to the URL adding a ? if there s no query string yet .
2,255
public static String addQueryStringFragment ( String url , String fragment ) { StringBuilder newUrl = new StringBuilder ( url ) ; if ( fragment . startsWith ( "?" ) || fragment . startsWith ( "&" ) ) { fragment = fragment . substring ( 1 ) ; } if ( ! url . endsWith ( "?" ) && ! url . endsWith ( "&" ) ) { if ( url . contains ( "?" ) ) { newUrl . append ( '&' ) ; } else { newUrl . append ( '?' ) ; } } return newUrl . append ( fragment ) . toString ( ) ; }
Adds a query string fragment to the URL adding a ? if there s no query string yet .
2,256
public static void zipFiles ( List < File > files , OutputStream outputStream ) throws IOException { ZipOutputStream zos = new ZipOutputStream ( outputStream ) ; for ( File file : files ) { if ( file . isDirectory ( ) ) { addFolderToZip ( "" , file , zos ) ; } else { addFileToZip ( "" , file , zos ) ; } } zos . finish ( ) ; }
Zips a collection of files to a destination zip output stream .
2,257
public static void zipFiles ( List < File > files , File zipFile ) throws IOException { OutputStream os = new BufferedOutputStream ( new FileOutputStream ( zipFile ) ) ; try { zipFiles ( files , os ) ; } finally { IOUtils . closeQuietly ( os ) ; } }
Zips a collection of files to a destination zip file .
2,258
public static void unZipFiles ( InputStream inputStream , File outputFolder ) throws IOException { ZipInputStream zis = new ZipInputStream ( inputStream ) ; ZipEntry ze = zis . getNextEntry ( ) ; while ( ze != null ) { File file = new File ( outputFolder , ze . getName ( ) ) ; OutputStream os = new BufferedOutputStream ( FileUtils . openOutputStream ( file ) ) ; try { IOUtils . copy ( zis , os ) ; } finally { IOUtils . closeQuietly ( os ) ; } zis . closeEntry ( ) ; ze = zis . getNextEntry ( ) ; } }
Unzips a zip from an input stream into an output folder .
2,259
public static void unZipFiles ( File zipFile , File outputFolder ) throws IOException { InputStream is = new BufferedInputStream ( new FileInputStream ( zipFile ) ) ; try { unZipFiles ( is , outputFolder ) ; } finally { IOUtils . closeQuietly ( is ) ; } }
Unzips a zip file into an output folder .
2,260
private static void addFolderToZip ( String path , File folder , ZipOutputStream zos ) throws IOException { String currentPath = StringUtils . isNotEmpty ( path ) ? path + "/" + folder . getName ( ) : folder . getName ( ) ; for ( File file : folder . listFiles ( ) ) { if ( file . isDirectory ( ) ) { addFolderToZip ( currentPath , file , zos ) ; } else { addFileToZip ( currentPath , file , zos ) ; } } }
Adds a directory to the current zip
2,261
private static void addFileToZip ( String path , File file , ZipOutputStream zos ) throws IOException { String currentPath = StringUtils . isNotEmpty ( path ) ? path + "/" + file . getName ( ) : file . getName ( ) ; zos . putNextEntry ( new ZipEntry ( currentPath ) ) ; InputStream is = new BufferedInputStream ( new FileInputStream ( file ) ) ; try { IOUtils . copy ( is , zos ) ; } finally { IOUtils . closeQuietly ( is ) ; } zos . closeEntry ( ) ; }
Adds a file to the current zip output stream
2,262
@ SuppressWarnings ( "unchecked" ) public static Map deepMerge ( Map dst , Map src ) { if ( dst != null && src != null ) { for ( Object key : src . keySet ( ) ) { if ( src . get ( key ) instanceof Map && dst . get ( key ) instanceof Map ) { Map originalChild = ( Map ) dst . get ( key ) ; Map newChild = ( Map ) src . get ( key ) ; dst . put ( key , deepMerge ( originalChild , newChild ) ) ; } else { dst . put ( key , src . get ( key ) ) ; } } } return dst ; }
Deep merges two maps
2,263
public void init ( ) { for ( Resource resource : resources ) { if ( resource . exists ( ) ) { try ( InputStream in = resource . getInputStream ( ) ) { readPropertyFile ( in ) ; } catch ( IOException ex ) { log . debug ( "Unable to load queries from " + resource . getDescription ( ) , ex ) ; } } else { log . info ( "Query file at {} not found. Ignoring it..." , resource . getDescription ( ) ) ; } } }
Checks and starts the reading of the given Resources .
2,264
private List < String > getIdList ( final List < ? extends AuditModel > toDelete ) { List < String > ids = new ArrayList < > ( toDelete . size ( ) ) ; for ( AuditModel auditModel : toDelete ) { ids . add ( auditModel . getId ( ) ) ; } return ids ; }
Gets the list of Id s of the given List of Models .
2,265
@ SuppressWarnings ( "uncheck" ) protected Iterable < T > returnList ( final Find find ) { return ( Iterable < T > ) find . as ( clazz ) ; }
Actually makes the transformation form Jongo to List of Objects .
2,266
protected String getQueryFor ( final String key ) { log . trace ( "Trying to get query for {} " , key ) ; String query = queries . get ( key ) ; log . trace ( "Query found {} for key {}" , query , key ) ; if ( query == null ) { log . error ( "Query for {} key does not exist" , key ) ; throw new IllegalArgumentException ( "Query for key " + key + " does not exist" ) ; } else if ( StringUtils . isBlank ( query ) ) { log . error ( "Query for key {} can't be blank or be only whitespace" , key ) ; throw new IllegalArgumentException ( "Query for key " + key + " can't be blank or be only whitespace" ) ; } return query . trim ( ) . replaceAll ( "\\s+" , " " ) ; }
Get the query string for a given key
2,267
public BaasResult < BaasDocument > refreshSync ( boolean withAcl ) { BaasBox box = BaasBox . getDefaultChecked ( ) ; if ( id == null ) throw new IllegalStateException ( "this document is not bound to any remote entity" ) ; Refresh refresh = new Refresh ( box , this , withAcl , RequestOptions . DEFAULT , null ) ; return box . submitSync ( refresh ) ; }
Synchronously refresh the content of this document
2,268
public BaasResult < Void > deleteSync ( ) { if ( id == null ) throw new IllegalStateException ( "this document is not bound to any remote entity" ) ; BaasBox box = BaasBox . getDefaultChecked ( ) ; Delete delete = new Delete ( box , this , RequestOptions . DEFAULT , null ) ; return box . submitSync ( delete ) ; }
Syncrhonously deletes this document on the server .
2,269
public BaasResult < BaasDocument > saveSync ( SaveMode mode , BaasACL acl ) { BaasBox box = BaasBox . getDefaultChecked ( ) ; if ( mode == null ) throw new IllegalArgumentException ( "mode cannot be null" ) ; Save save = new Save ( box , mode , acl , this , RequestOptions . DEFAULT , null ) ; return box . submitSync ( save ) ; }
Synchronously saves the document on the server with initial acl
2,270
public int number ( CharSequence seq ) { StateInfo info = getStateInfo ( seq ) ; return info . isInFinalState ( ) ? info . getHash ( ) : - 1 ; }
Compute the perfect hash code of the given character sequence .
2,271
public String toDot ( ) { StringBuilder dotBuilder = new StringBuilder ( ) ; dotBuilder . append ( "digraph G {\n" ) ; for ( int state = 0 ; state < d_stateOffsets . size ( ) ; ++ state ) { for ( int trans = d_stateOffsets . get ( state ) ; trans < transitionsUpperBound ( state ) ; ++ trans ) dotBuilder . append ( String . format ( "%d -> %d [label=\"%c\"]\n" , state , d_transitionTo . get ( trans ) , d_transitionChars [ trans ] ) ) ; if ( d_finalStates . get ( state ) ) dotBuilder . append ( String . format ( "%d [peripheries=2,label=\"%d (%d)\"];\n" , state , state , d_stateNSuffixes . get ( state ) ) ) ; else dotBuilder . append ( String . format ( "%d [label=\"%d (%d)\"];\n" , state , state , d_stateNSuffixes . get ( state ) ) ) ; } dotBuilder . append ( "}" ) ; return dotBuilder . toString ( ) ; }
Give the Graphviz dot representation of this automaton . States will also list the number of suffixes under that state .
2,272
private void computeStateSuffixesTopological ( final int initialState , final int magicMarker ) { for ( Iterator < Integer > iterator = sortStatesTopological ( initialState ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Integer currentState = iterator . next ( ) ; int currentSuffixes = d_stateNSuffixes . get ( currentState ) ; if ( currentSuffixes == magicMarker ) { int trans = d_stateOffsets . get ( currentState ) ; int transUpperBound = transitionsUpperBound ( currentState ) ; if ( trans < transUpperBound ) { int suffixes = d_finalStates . get ( currentState ) ? 1 : 0 ; for ( ; trans < transUpperBound ; ++ trans ) { int childState = d_transitionTo . get ( trans ) ; assert d_stateNSuffixes . get ( childState ) != magicMarker : "suffxies should have been calculated for state " + childState ; suffixes += d_stateNSuffixes . get ( childState ) ; } d_stateNSuffixes . set ( currentState , suffixes ) ; } else { d_stateNSuffixes . set ( currentState , d_finalStates . get ( currentState ) ? 1 : 0 ) ; } } } }
Iteratively computes the number of suffixes by topological order
2,273
protected int transitionsUpperBound ( int state ) { return state + 1 < d_stateOffsets . size ( ) ? d_stateOffsets . get ( state + 1 ) : d_transitionChars . length ; }
Calculate the upper bound for this state in the transition table .
2,274
protected int findTransition ( int state , char c ) { int start = d_stateOffsets . get ( state ) ; int end = transitionsUpperBound ( state ) - 1 ; while ( end >= start ) { int mid = start + ( ( end - start ) / 2 ) ; if ( d_transitionChars [ mid ] > c ) end = mid - 1 ; else if ( d_transitionChars [ mid ] < c ) start = mid + 1 ; else return mid ; } return - 1 ; }
Find the transition for the given character in the given state . Since the transitions are ordered by character we can use a binary search .
2,275
private boolean containsSeq ( String seq ) { int state = 0 ; for ( int i = 0 ; i < seq . length ( ) ; i ++ ) { state = next ( state , seq . charAt ( i ) ) ; if ( state == - 1 ) return false ; } return d_finalStates . get ( state ) ; }
Check whether the dictionary contains the given sequence .
2,276
public short getOrElse ( String key , short defaultValue ) { int hash = d_keys . number ( key ) ; if ( hash == - 1 ) return defaultValue ; return d_values [ hash - 1 ] ; }
Get the value associated with a key returning a default value is it is not in the mapping .
2,277
public JsonWriter name ( String name ) throws IOException { if ( name == null ) { throw new NullPointerException ( "name == null" ) ; } beforeName ( ) ; string ( name ) ; return this ; }
Encodes the property name .
2,278
private String nextLiteral ( boolean assignOffsetsOnly ) throws IOException { StringBuilder builder = null ; valuePos = - 1 ; valueLength = 0 ; int i = 0 ; findNonLiteralCharacter : while ( true ) { for ( ; pos + i < limit ; i ++ ) { switch ( buffer [ pos + i ] ) { case '/' : case '\\' : case ';' : case '#' : case '=' : checkLenient ( ) ; case '{' : case '}' : case '[' : case ']' : case ':' : case ',' : case ' ' : case '\t' : case '\f' : case '\r' : case '\n' : break findNonLiteralCharacter ; } } if ( i < buffer . length ) { if ( fillBuffer ( i + 1 ) ) { continue ; } else { buffer [ limit ] = '\0' ; break ; } } if ( builder == null ) { builder = new StringBuilder ( ) ; } builder . append ( buffer , pos , i ) ; valueLength += i ; pos += i ; i = 0 ; if ( ! fillBuffer ( 1 ) ) { break ; } } String result ; if ( assignOffsetsOnly && builder == null ) { valuePos = pos ; result = null ; } else if ( skipping ) { result = "skipped!" ; } else if ( builder == null ) { result = stringPool . get ( buffer , pos , i ) ; } else { builder . append ( buffer , pos , i ) ; result = builder . toString ( ) ; } valueLength += i ; pos += i ; return result ; }
Reads the value up to but not including any delimiter characters . This does not consume the delimiter character .
2,279
private JsonToken readLiteral ( ) throws IOException { value = nextLiteral ( true ) ; if ( valueLength == 0 ) { throw syntaxError ( "Expected literal value" ) ; } token = decodeLiteral ( ) ; if ( token == JsonToken . STRING ) { checkLenient ( ) ; } return token ; }
Reads a null boolean numeric or unquoted string literal value .
2,280
private JsonToken decodeNumber ( char [ ] chars , int offset , int length ) { int i = offset ; int c = chars [ i ] ; if ( c == '-' ) { c = chars [ ++ i ] ; } if ( c == '0' ) { c = chars [ ++ i ] ; } else if ( c >= '1' && c <= '9' ) { c = chars [ ++ i ] ; while ( c >= '0' && c <= '9' ) { c = chars [ ++ i ] ; } } else { return JsonToken . STRING ; } if ( c == '.' ) { c = chars [ ++ i ] ; while ( c >= '0' && c <= '9' ) { c = chars [ ++ i ] ; } } if ( c == 'e' || c == 'E' ) { c = chars [ ++ i ] ; if ( c == '+' || c == '-' ) { c = chars [ ++ i ] ; } if ( c >= '0' && c <= '9' ) { c = chars [ ++ i ] ; while ( c >= '0' && c <= '9' ) { c = chars [ ++ i ] ; } } else { return JsonToken . STRING ; } } if ( i == offset + length ) { return JsonToken . NUMBER ; } else { return JsonToken . STRING ; } }
Determine whether the characters is a JSON number . Numbers are of the form - 12 . 34e + 56 . Fractional and exponential parts are optional . Leading zeroes are not allowed in the value or exponential part but are allowed in the fraction .
2,281
private JsonToken advance ( ) throws IOException { peek ( ) ; JsonToken result = token ; token = null ; value = null ; name = null ; return result ; }
Advances the cursor in the JSON stream to the next token .
2,282
public void skipValue ( ) throws IOException { skipping = true ; try { int count = 0 ; do { JsonToken token = advance ( ) ; if ( token == JsonToken . BEGIN_ARRAY || token == JsonToken . BEGIN_OBJECT ) { count ++ ; } else if ( token == JsonToken . END_ARRAY || token == JsonToken . END_OBJECT ) { count -- ; } } while ( count != 0 ) ; } finally { skipping = false ; } }
Skips the next value recursively . If it is an object or array all nested elements are skipped . This method is intended for use when the JSON token stream contains unrecognized or unhandled values .
2,283
public DictionaryBuilder add ( CharSequence seq ) throws DictionaryBuilderException { if ( d_finalized ) throw new DictionaryBuilderException ( "Cannot add a sequence to a finalized DictionaryBuilder." ) ; if ( d_prevSeq != null && compareCharacterSequences ( d_prevSeq , seq ) >= 0 ) throw new DictionaryBuilderException ( String . format ( "Sequences are not added in lexicographic order: %s %s" , d_prevSeq , seq ) ) ; d_prevSeq = seq ; int i = 0 ; State curState = d_startState ; for ( int len = seq . length ( ) ; i < len ; i ++ ) { State nextState = curState . move ( seq . charAt ( i ) ) ; if ( nextState != null ) curState = nextState ; else break ; } if ( curState . hasOutgoing ( ) ) replaceOrRegisterIterative ( curState ) ; addSuffix ( curState , seq . subSequence ( i , seq . length ( ) ) ) ; ++ d_nSeqs ; return this ; }
Add a character sequence .
2,284
public DictionaryBuilder addAll ( Collection < ? extends CharSequence > seqs ) throws DictionaryBuilderException { for ( CharSequence seq : seqs ) add ( seq ) ; return this ; }
Add all sequences from a lexicographically sorted collection .
2,285
public void reduce ( Character otherChar ) { Set < Integer > seen = new HashSet < > ( ) ; Queue < LevenshteinAutomatonState > q = new LinkedList < > ( ) ; q . add ( this ) ; while ( ! q . isEmpty ( ) ) { LevenshteinAutomatonState s = q . poll ( ) ; if ( seen . contains ( System . identityHashCode ( s ) ) ) continue ; LevenshteinAutomatonState otherTo = s . transitions . get ( otherChar ) ; if ( otherTo == null ) { for ( LevenshteinAutomatonState toState : s . transitions . values ( ) ) q . add ( toState ) ; seen . add ( System . identityHashCode ( s ) ) ; continue ; } Set < Character > remove = new HashSet < > ( ) ; for ( Entry < Character , LevenshteinAutomatonState > trans : s . transitions . entrySet ( ) ) if ( ! trans . getKey ( ) . equals ( otherChar ) && trans . getValue ( ) == otherTo ) remove . add ( trans . getKey ( ) ) ; for ( Character c : remove ) s . transitions . remove ( c ) ; if ( remove . size ( ) != 0 ) s . d_recomputeHash = true ; seen . add ( System . identityHashCode ( s ) ) ; for ( LevenshteinAutomatonState toState : s . transitions . values ( ) ) q . add ( toState ) ; } }
Reduce the set of outgoing transitions by removing transitions that are also captured by the other - transition . The other - transition are transitions with the given character .
2,286
public static RequestToken fetchData ( String id , BaasHandler < JsonObject > handler ) { return fetchData ( id , RequestOptions . DEFAULT , handler ) ; }
Asynchronously retrieves named assets data If the named asset is a document the document is retrieved otherwise attached data to the file are returned . This version of the method uses default priority .
2,287
public static RequestToken fetchData ( String id , int flags , BaasHandler < JsonObject > handler ) { if ( id == null ) throw new IllegalArgumentException ( "asset id cannot be null" ) ; BaasBox box = BaasBox . getDefaultChecked ( ) ; AssetDataRequest req = new AssetDataRequest ( box , id , flags , handler ) ; return box . submitAsync ( req ) ; }
Asynchronously retrieves named assets data If the named asset is a document the document is retrieved otherwise attached data to the file are returned .
2,288
public static BaasResult < JsonObject > fetchDataSync ( String id ) { if ( id == null ) throw new IllegalArgumentException ( "asset id cannot be null" ) ; BaasBox box = BaasBox . getDefaultChecked ( ) ; AssetDataRequest req = new AssetDataRequest ( box , id , RequestOptions . DEFAULT , null ) ; return box . submitSync ( req ) ; }
Synchronously retrieves named assets data If the named asset is a document the document is retrieved otherwise attached data to the file are returned .
2,289
public void addTransition ( Character c , State s ) { transitions . put ( c , s ) ; d_recomputeHash = true ; }
Add a transition to the state . If a transition with the provided character already exists it will be replaced .
2,290
public RequestToken rest ( int method , String endpoint , JsonArray body , int flags , boolean authenticate , BaasHandler < JsonObject > jsonHandler ) { return mRest . async ( RestImpl . methodFrom ( method ) , endpoint , body , authenticate , flags , jsonHandler ) ; }
Asynchronously sends a raw rest request to the server that is specified by the parameters passed in
2,291
public RequestToken rest ( int method , String endpoint , JsonArray body , boolean authenticate , BaasHandler < JsonObject > handler ) { return rest ( method , endpoint , body , 0 , authenticate , handler ) ; }
Asynchronously sends a raw rest request to the server that is specified by the parameters passed in .
2,292
public BaasResult < JsonObject > restSync ( int method , String endpoint , JsonArray body , boolean authenticate ) { return mRest . sync ( RestImpl . methodFrom ( method ) , endpoint , body , authenticate ) ; }
Synchronously sends a raw rest request to the server that is specified by the parameters passed in .
2,293
public static RequestToken loadAndResume ( Bundle bundle , String name , BaasHandler < ? > handler ) { if ( bundle == null ) throw new IllegalArgumentException ( "bunlde cannot be null" ) ; if ( name == null ) throw new IllegalArgumentException ( "name cannot be null" ) ; RequestToken token = bundle . getParcelable ( name ) ; if ( token != null && token . resume ( handler ) ) { return token ; } return null ; }
Loads a request token from the bundle and immediately tries to resume the request with handler
2,294
public boolean resume ( BaasHandler < ? > handler ) { return BaasBox . getDefaultChecked ( ) . resume ( this , handler == null ? BaasHandler . NOOP : handler ) ; }
Resumes a suspended asynchronous request with the new provided handler
2,295
public boolean suspendAndSave ( Bundle bundle , String name ) { if ( bundle == null ) throw new IllegalArgumentException ( "bunlde cannot be null" ) ; if ( name == null ) throw new IllegalArgumentException ( "name cannot be null" ) ; if ( suspend ( ) ) { bundle . putParcelable ( name , this ) ; return true ; } else { return false ; } }
Suspends a request and immediately save it in a bundle
2,296
public String getString ( int index , String otherwise ) { Object o = list . get ( index ) ; if ( o == null ) return otherwise ; if ( o instanceof String ) return ( String ) o ; if ( o instanceof byte [ ] ) return encodeBinary ( ( byte [ ] ) o ) ; throw new JsonException ( "not a string" ) ; }
Returns the String at index or otherwise if not found
2,297
public RequestToken follow ( int flags , BaasHandler < BaasUser > handler ) { BaasBox box = BaasBox . getDefaultChecked ( ) ; Follow follow = new Follow ( box , true , this , RequestOptions . DEFAULT , handler ) ; return box . submitAsync ( follow ) ; }
Asynchronously requests to follow the user .
2,298
public boolean isCurrent ( ) { BaasUser current = current ( ) ; if ( current == null ) return false ; Logger . debug ( "Current username is %s and mine is %s" , current . username , username ) ; return current . username . equals ( username ) ; }
Checks if this user is the currently logged in user on this device .
2,299
public Set < String > getRoles ( ) { HashSet < String > rolescopy ; rolescopy = new HashSet < > ( roles ) ; return Collections . unmodifiableSet ( rolescopy ) ; }
Returns an unmodifialble set of the roles to which the user belongs if it s available