idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
5,900 | protected void registerResponses ( Swagger swagger , Operation operation , Method method ) { for ( Return aReturn : ControllerUtil . getReturns ( method ) ) { registerResponse ( swagger , operation , aReturn ) ; } } | Registers the declared responses for the operation . |
5,901 | protected void registerResponse ( Swagger swagger , Operation operation , Return aReturn ) { Response response = new Response ( ) ; response . setDescription ( translate ( aReturn . descriptionKey ( ) , aReturn . description ( ) ) ) ; Class < ? > resultType = aReturn . onResult ( ) ; if ( Exception . class . isAssignableFrom ( resultType ) ) { Property errorProperty = registerErrorModel ( swagger ) ; response . setSchema ( errorProperty ) ; } else if ( Void . class != resultType ) { if ( resultType . isArray ( ) ) { Class < ? > componentClass = resultType . getComponentType ( ) ; ArrayProperty arrayProperty = new ArrayProperty ( ) ; Property componentProperty = getSwaggerProperty ( swagger , componentClass ) ; arrayProperty . setItems ( componentProperty ) ; response . setSchema ( arrayProperty ) ; } else { Property returnProperty = getSwaggerProperty ( swagger , resultType ) ; response . setSchema ( returnProperty ) ; } } for ( Class < ? extends ReturnHeader > returnHeader : aReturn . headers ( ) ) { Tag headerTag = getModelTag ( returnHeader ) ; ReturnHeader header = ClassUtil . newInstance ( returnHeader ) ; Property property = getSwaggerProperty ( swagger , header . getHeaderType ( ) ) ; if ( property instanceof ArrayProperty ) { ArrayProperty arrayProperty = ( ArrayProperty ) property ; } property . setName ( headerTag . getName ( ) ) ; property . setDescription ( headerTag . getDescription ( ) ) ; response . addHeader ( property . getName ( ) , property ) ; } operation . response ( aReturn . code ( ) , response ) ; } | Registers a declared response for the operation . |
5,902 | protected RefProperty registerErrorModel ( Swagger swagger ) { String ref = Error . class . getSimpleName ( ) ; if ( swagger . getDefinitions ( ) != null && swagger . getDefinitions ( ) . containsKey ( ref ) ) { return new RefProperty ( ref ) ; } ModelImpl model = new ModelImpl ( ) ; swagger . addDefinition ( ref , model ) ; model . setDescription ( "an error message" ) ; model . addProperty ( "statusCode" , new IntegerProperty ( ) . readOnly ( ) . description ( "http status code" ) ) ; model . addProperty ( "statusMessage" , new StringProperty ( ) . readOnly ( ) . description ( "description of the http status code" ) ) ; model . addProperty ( "requestMethod" , new StringProperty ( ) . readOnly ( ) . description ( "http request method" ) ) ; model . addProperty ( "requestUri" , new StringProperty ( ) . readOnly ( ) . description ( "http request path" ) ) ; model . addProperty ( "message" , new StringProperty ( ) . readOnly ( ) . description ( "application message" ) ) ; if ( settings . isDev ( ) ) { model . addProperty ( "stacktrace" , new StringProperty ( ) . readOnly ( ) . description ( "application stacktrace" ) ) ; } return new RefProperty ( ref ) ; } | Manually register the Pippo Error class as Swagger model . |
5,903 | protected void registerSecurity ( Swagger swagger , Operation operation , Method method ) { RequireToken requireToken = ClassUtil . getAnnotation ( method , RequireToken . class ) ; if ( requireToken != null ) { String apiKeyName = requireToken . value ( ) ; if ( swagger . getSecurityDefinitions ( ) == null || ! swagger . getSecurityDefinitions ( ) . containsKey ( apiKeyName ) ) { ApiKeyAuthDefinition security = new ApiKeyAuthDefinition ( ) ; security . setName ( apiKeyName ) ; security . setIn ( In . HEADER ) ; security . setType ( "apiKey" ) ; swagger . addSecurityDefinition ( apiKeyName , security ) ; } operation . addSecurity ( apiKeyName , Collections . emptyList ( ) ) ; } BasicAuth basicAuth = ClassUtil . getAnnotation ( method , BasicAuth . class ) ; if ( basicAuth != null ) { if ( swagger . getSecurityDefinitions ( ) == null || ! swagger . getSecurityDefinitions ( ) . containsKey ( "basic" ) ) { BasicAuthDefinition security = new BasicAuthDefinition ( ) ; swagger . addSecurityDefinition ( "basic" , security ) ; } operation . addSecurity ( "basic" , Collections . emptyList ( ) ) ; } } | Register authentication security . |
5,904 | protected Property getSwaggerProperty ( Swagger swagger , Class < ? > objectClass ) { Property swaggerProperty = null ; if ( byte . class == objectClass || Byte . class == objectClass ) { swaggerProperty = new StringProperty ( "byte" ) ; } else if ( char . class == objectClass || Character . class == objectClass ) { StringProperty property = new StringProperty ( ) ; property . setMaxLength ( 1 ) ; swaggerProperty = property ; } else if ( short . class == objectClass || Short . class == objectClass ) { IntegerProperty property = new IntegerProperty ( ) ; property . setMinimum ( BigDecimal . valueOf ( Short . MIN_VALUE ) ) ; property . setMaximum ( BigDecimal . valueOf ( Short . MAX_VALUE ) ) ; swaggerProperty = property ; } else if ( int . class == objectClass || Integer . class == objectClass ) { swaggerProperty = new IntegerProperty ( ) ; } else if ( long . class == objectClass || Long . class == objectClass ) { swaggerProperty = new LongProperty ( ) ; } else if ( float . class == objectClass || Float . class == objectClass ) { swaggerProperty = new FloatProperty ( ) ; } else if ( double . class == objectClass || Double . class == objectClass ) { swaggerProperty = new DoubleProperty ( ) ; } else if ( BigDecimal . class == objectClass ) { swaggerProperty = new DecimalProperty ( ) ; } else if ( boolean . class == objectClass || Boolean . class == objectClass ) { swaggerProperty = new BooleanProperty ( ) ; } else if ( String . class == objectClass ) { swaggerProperty = new StringProperty ( ) ; } else if ( Date . class == objectClass || Timestamp . class == objectClass ) { swaggerProperty = new DateTimeProperty ( ) ; } else if ( java . sql . Date . class == objectClass ) { swaggerProperty = new DateProperty ( ) ; } else if ( java . sql . Time . class == objectClass ) { StringProperty property = new StringProperty ( ) ; property . setPattern ( "HH:mm:ss" ) ; swaggerProperty = property ; } else if ( UUID . class == objectClass ) { swaggerProperty = new UUIDProperty ( ) ; } else if ( objectClass . isEnum ( ) ) { StringProperty property = new StringProperty ( ) ; List < String > enumValues = new ArrayList < > ( ) ; for ( Object enumValue : objectClass . getEnumConstants ( ) ) { enumValues . add ( ( ( Enum ) enumValue ) . name ( ) ) ; } property . setEnum ( enumValues ) ; swaggerProperty = property ; } else if ( FileItem . class == objectClass ) { swaggerProperty = new FileProperty ( ) ; } else { String modelRef = registerModel ( swagger , objectClass ) ; swaggerProperty = new RefProperty ( modelRef ) ; } return swaggerProperty ; } | Returns the appropriate Swagger Property instance for a given object class . |
5,905 | protected Tag getControllerTag ( Class < ? extends Controller > controllerClass ) { if ( controllerClass . isAnnotationPresent ( ApiOperations . class ) ) { ApiOperations annotation = controllerClass . getAnnotation ( ApiOperations . class ) ; io . swagger . models . Tag tag = new io . swagger . models . Tag ( ) ; tag . setName ( Optional . fromNullable ( Strings . emptyToNull ( annotation . tag ( ) ) ) . or ( controllerClass . getSimpleName ( ) ) ) ; tag . setDescription ( translate ( annotation . descriptionKey ( ) , annotation . description ( ) ) ) ; if ( ! Strings . isNullOrEmpty ( annotation . externalDocs ( ) ) ) { ExternalDocs docs = new ExternalDocs ( ) ; docs . setUrl ( annotation . externalDocs ( ) ) ; tag . setExternalDocs ( docs ) ; } if ( ! Strings . isNullOrEmpty ( tag . getDescription ( ) ) ) { return tag ; } } return null ; } | Returns the Tag for a controller . |
5,906 | protected Tag getModelTag ( Class < ? > modelClass ) { if ( modelClass . isAnnotationPresent ( ApiModel . class ) ) { ApiModel annotation = modelClass . getAnnotation ( ApiModel . class ) ; Tag tag = new Tag ( ) ; tag . setName ( Optional . fromNullable ( Strings . emptyToNull ( annotation . name ( ) ) ) . or ( modelClass . getSimpleName ( ) ) ) ; tag . setDescription ( translate ( annotation . descriptionKey ( ) , annotation . description ( ) ) ) ; return tag ; } Tag tag = new Tag ( ) ; tag . setName ( modelClass . getName ( ) ) ; return tag ; } | Returns the tag of the model . This ref is either explicitly named or it is generated from the model class name . |
5,907 | protected String getDescription ( Parameter parameter ) { if ( parameter . isAnnotationPresent ( Desc . class ) ) { Desc annotation = parameter . getAnnotation ( Desc . class ) ; return translate ( annotation . key ( ) , annotation . value ( ) ) ; } return null ; } | Returns the description of a parameter . |
5,908 | protected boolean isRequired ( Parameter parameter ) { return parameter . isAnnotationPresent ( Body . class ) || parameter . isAnnotationPresent ( Required . class ) || parameter . isAnnotationPresent ( NotNull . class ) ; } | Determines if a parameter is Required or not . |
5,909 | protected String translate ( String messageKey , String defaultMessage ) { if ( messages == null || Strings . isNullOrEmpty ( messageKey ) ) { return Strings . emptyToNull ( defaultMessage ) ; } return Strings . emptyToNull ( messages . getWithDefault ( messageKey , defaultMessage , defaultLanguage ) ) ; } | Attempts to provide a localized message . |
5,910 | public final void init ( String ... packageNames ) { Collection < Class < ? > > classes = discoverClasses ( packageNames ) ; if ( classes . isEmpty ( ) ) { log . warn ( "No annotated controllers found in package(s) '{}'" , Arrays . toString ( packageNames ) ) ; return ; } log . debug ( "Found {} controller classes in {} package(s)" , classes . size ( ) , packageNames . length ) ; init ( classes ) ; } | Scans identifies and registers annotated controller methods for the current runtime settings . |
5,911 | public final void init ( Class < ? extends Controller > ... controllers ) { List < Class < ? > > classes = Arrays . asList ( controllers ) ; init ( classes ) ; } | Register all methods in the specified controller classes . |
5,912 | private void registerControllerMethods ( Map < Method , Class < ? extends Annotation > > discoveredMethods ) { Collection < Method > methods = sortMethods ( discoveredMethods . keySet ( ) ) ; Map < Class < ? extends Controller > , Set < String > > controllers = new HashMap < > ( ) ; for ( Method method : methods ) { Class < ? extends Controller > controllerClass = ( Class < ? extends Controller > ) method . getDeclaringClass ( ) ; if ( ! controllers . containsKey ( controllerClass ) ) { Set < String > paths = collectPaths ( controllerClass ) ; controllers . put ( controllerClass , paths ) ; } Class < ? extends Annotation > httpMethodAnnotationClass = discoveredMethods . get ( method ) ; Annotation httpMethodAnnotation = method . getAnnotation ( httpMethodAnnotationClass ) ; String httpMethod = httpMethodAnnotation . annotationType ( ) . getAnnotation ( HttpMethod . class ) . value ( ) ; String [ ] methodPaths = ClassUtil . executeDeclaredMethod ( httpMethodAnnotation , "value" ) ; Set < String > controllerPaths = controllers . get ( controllerClass ) ; if ( controllerPaths . isEmpty ( ) ) { controllerPaths . add ( "" ) ; } for ( String controllerPath : controllerPaths ) { if ( methodPaths . length == 0 ) { String fullPath = StringUtils . addStart ( StringUtils . removeEnd ( controllerPath , "/" ) , "/" ) ; ControllerHandler handler = new ControllerHandler ( injector , controllerClass , method . getName ( ) ) ; handler . validateMethodArgs ( fullPath ) ; RouteRegistration registration = new RouteRegistration ( httpMethod , fullPath , handler ) ; configureRegistration ( registration , method ) ; routeRegistrations . add ( registration ) ; } else { for ( String methodPath : methodPaths ) { String path = Joiner . on ( "/" ) . skipNulls ( ) . join ( StringUtils . removeEnd ( controllerPath , "/" ) , StringUtils . removeStart ( methodPath , "/" ) ) ; String fullPath = StringUtils . addStart ( StringUtils . removeEnd ( path , "/" ) , "/" ) ; ControllerHandler handler = new ControllerHandler ( injector , controllerClass , method . getName ( ) ) ; handler . validateMethodArgs ( fullPath ) ; RouteRegistration registration = new RouteRegistration ( httpMethod , fullPath , handler ) ; configureRegistration ( registration , method ) ; routeRegistrations . add ( registration ) ; } } } } } | Register the controller methods as Routes . |
5,913 | public MailRequest newTextMailRequest ( String subject , String body ) { return createMailRequest ( generateRequestId ( ) , false , subject , body ) ; } | Creates a plain text MailRequest with the specified subject and body . A request id is automatically generated . |
5,914 | public MailRequest newTextMailRequest ( String requestId , String subject , String body ) { return createMailRequest ( requestId , false , subject , body ) ; } | Creates a plan text MailRequest with the specified subject and body . The request id is supplied . |
5,915 | public MailRequest newHtmlMailRequest ( String subject , String body ) { return createMailRequest ( generateRequestId ( ) , true , subject , body ) ; } | Creates an html MailRequest with the specified subject and body . The request id is automatically generated . |
5,916 | public MailRequest newHtmlMailRequest ( String requestId , String subject , String body ) { return createMailRequest ( requestId , true , subject , body ) ; } | Creates an html MailRequest with the specified subject and body . The request id is supplied . |
5,917 | public MailRequest newTextTemplateMailRequest ( String subjectTemplate , String textTemplateName , Map < String , Object > parameters ) { return createTemplateMailRequest ( generateRequestId ( ) , subjectTemplate , textTemplateName , false , parameters ) ; } | Creates a MailRequest from the specified template . The request id is automatically generated . |
5,918 | public MailRequest newHtmlTemplateMailRequest ( String requestId , String subjectTemplate , String htmlTemplateName , Map < String , Object > parameters ) { return createTemplateMailRequest ( requestId , subjectTemplate , htmlTemplateName , true , parameters ) ; } | Creates a MailRequest from the specified template . The request id is supplied . |
5,919 | public static PippoSettings getPippoSettings ( Settings settings ) { RuntimeMode runtimeMode = RuntimeMode . PROD ; for ( RuntimeMode mode : RuntimeMode . values ( ) ) { if ( mode . name ( ) . equalsIgnoreCase ( settings . getMode ( ) . toString ( ) ) ) { runtimeMode = mode ; } } final Properties properties = settings . toProperties ( ) ; final PippoSettings pippoSettings = new PippoSettings ( runtimeMode ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { Object value = entry . getValue ( ) ; String propertyValue ; if ( value instanceof Collection ) { propertyValue = Optional . fromNullable ( value ) . or ( "" ) . toString ( ) ; propertyValue = propertyValue . substring ( 1 , propertyValue . length ( ) - 1 ) ; } else { propertyValue = Optional . fromNullable ( value ) . or ( "" ) . toString ( ) ; } String propertyName = entry . getKey ( ) . toString ( ) ; pippoSettings . overrideSetting ( propertyName , propertyValue ) ; } return pippoSettings ; } | Convert Fathom Settings into PippoSettings |
5,920 | protected synchronized void readFile ( ) { if ( realmFile != null && realmFile . exists ( ) && ( realmFile . lastModified ( ) != lastModified ) ) { lastModified = realmFile . lastModified ( ) ; try { Preconditions . checkArgument ( realmFile . canRead ( ) , "The file '{}' can not be read!" , realmFile ) ; Config config = ConfigFactory . parseFile ( realmFile ) ; super . setup ( config ) ; } catch ( Exception e ) { log . error ( "Failed to read {}" , realmFile , e ) ; } } } | Reads the realm file and rebuilds the in - memory lookup tables . |
5,921 | public static ACE newInstance ( final AceType type ) { final ACE ace = new ACE ( ) ; ace . setType ( type ) ; return ace ; } | Creates a new ACE instance . |
5,922 | int parse ( final IntBuffer buff , final int start ) { int pos = start ; byte [ ] bytes = NumberFacility . getBytes ( buff . get ( pos ) ) ; type = AceType . parseValue ( bytes [ 0 ] ) ; flags = AceFlag . parseValue ( bytes [ 1 ] ) ; int size = NumberFacility . getInt ( bytes [ 3 ] , bytes [ 2 ] ) ; pos ++ ; rights = AceRights . parseValue ( NumberFacility . getReverseInt ( buff . get ( pos ) ) ) ; if ( type == AceType . ACCESS_ALLOWED_OBJECT_ACE_TYPE || type == AceType . ACCESS_DENIED_OBJECT_ACE_TYPE ) { pos ++ ; objectFlags = AceObjectFlags . parseValue ( NumberFacility . getReverseInt ( buff . get ( pos ) ) ) ; if ( objectFlags . getFlags ( ) . contains ( AceObjectFlags . Flag . ACE_OBJECT_TYPE_PRESENT ) ) { objectType = new byte [ 16 ] ; for ( int j = 0 ; j < 4 ; j ++ ) { pos ++ ; System . arraycopy ( NumberFacility . getBytes ( buff . get ( pos ) ) , 0 , objectType , j * 4 , 4 ) ; } } if ( objectFlags . getFlags ( ) . contains ( AceObjectFlags . Flag . ACE_INHERITED_OBJECT_TYPE_PRESENT ) ) { inheritedObjectType = new byte [ 16 ] ; for ( int j = 0 ; j < 4 ; j ++ ) { pos ++ ; System . arraycopy ( NumberFacility . getBytes ( buff . get ( pos ) ) , 0 , inheritedObjectType , j * 4 , 4 ) ; } } } pos ++ ; sid = new SID ( ) ; pos = sid . parse ( buff , pos ) ; int lastPos = start + ( size / 4 ) - 1 ; applicationData = new byte [ 4 * ( lastPos - pos ) ] ; int index = 0 ; while ( pos < lastPos ) { pos ++ ; System . arraycopy ( NumberFacility . getBytes ( buff . get ( pos ) ) , 0 , applicationData , index , 4 ) ; index += 4 ; } return pos ; } | Load the ACE from the buffer returning the last ACE segment position into the buffer . |
5,923 | public byte [ ] getApplicationData ( ) { return this . applicationData == null || this . applicationData . length == 0 ? null : Arrays . copyOf ( this . applicationData , this . applicationData . length ) ; } | Optional application data . The size of the application data is determined by the AceSize field . |
5,924 | public void setApplicationData ( final byte [ ] applicationData ) { this . applicationData = applicationData == null || applicationData . length == 0 ? null : Arrays . copyOf ( applicationData , applicationData . length ) ; } | Sets application data . |
5,925 | public int getSize ( ) { return 8 + ( objectFlags == null ? 0 : 4 ) + ( objectType == null ? 0 : 16 ) + ( inheritedObjectType == null ? 0 : 16 ) + ( sid == null ? 0 : sid . getSize ( ) ) + ( applicationData == null ? 0 : applicationData . length ) ; } | An unsigned 16 - bit integer that specifies the size in bytes of the ACE . The AceSize field can be greater than the sum of the individual fields but MUST be a multiple of 4 to ensure alignment on a DWORD boundary . In cases where the AceSize field encompasses additional data for the callback ACEs types that data is implementation - specific . Otherwise this additional data is not interpreted and MUST be ignored . |
5,926 | protected void install ( Module module ) { module . setSettings ( settings ) ; module . setServices ( services ) ; binder ( ) . install ( module ) ; } | Install a Fathom Module . |
5,927 | public static AceObjectFlags parseValue ( final int value ) { final AceObjectFlags res = new AceObjectFlags ( ) ; res . others = value ; for ( AceObjectFlags . Flag type : AceObjectFlags . Flag . values ( ) ) { if ( ( value & type . getValue ( ) ) == type . getValue ( ) ) { res . flags . add ( type ) ; res . others ^= type . getValue ( ) ; } } return res ; } | Parse flags given as int value . |
5,928 | public AceObjectFlags addFlag ( final Flag flag ) { if ( ! flags . contains ( flag ) ) { flags . add ( flag ) ; } return this ; } | Adds standard ACE object flag . |
5,929 | public static KeyStore openKeyStore ( File storeFile , String storePassword ) { String lc = storeFile . getName ( ) . toLowerCase ( ) ; String type = "JKS" ; String provider = null ; if ( lc . endsWith ( ".p12" ) || lc . endsWith ( ".pfx" ) ) { type = "PKCS12" ; provider = BC ; } try { KeyStore store ; if ( provider == null ) { store = KeyStore . getInstance ( type ) ; } else { store = KeyStore . getInstance ( type , provider ) ; } storeFile . getParentFile ( ) . mkdirs ( ) ; if ( storeFile . exists ( ) ) { FileInputStream fis = null ; try { fis = new FileInputStream ( storeFile ) ; store . load ( fis , storePassword . toCharArray ( ) ) ; } finally { if ( fis != null ) { fis . close ( ) ; } } } else { store . load ( null ) ; } return store ; } catch ( Exception e ) { throw new RuntimeException ( "Could not open keystore " + storeFile , e ) ; } } | Open a keystore . Store type is determined by file extension of name . If undetermined JKS is assumed . The keystore does not need to exist . |
5,930 | public static void saveKeyStore ( File targetStoreFile , KeyStore store , String password ) { File folder = targetStoreFile . getAbsoluteFile ( ) . getParentFile ( ) ; if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } File tmpFile = new File ( folder , Long . toHexString ( System . currentTimeMillis ( ) ) + ".tmp" ) ; FileOutputStream fos = null ; try { fos = new FileOutputStream ( tmpFile ) ; store . store ( fos , password . toCharArray ( ) ) ; fos . flush ( ) ; fos . close ( ) ; if ( targetStoreFile . exists ( ) ) { targetStoreFile . delete ( ) ; } tmpFile . renameTo ( targetStoreFile ) ; } catch ( IOException e ) { String message = e . getMessage ( ) . toLowerCase ( ) ; if ( message . contains ( "illegal key size" ) ) { throw new RuntimeException ( "Illegal Key Size! You might consider installing the JCE Unlimited Strength Jurisdiction Policy files for your JVM." ) ; } else { throw new RuntimeException ( "Could not save keystore " + targetStoreFile , e ) ; } } catch ( Exception e ) { throw new RuntimeException ( "Could not save keystore " + targetStoreFile , e ) ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { } } if ( tmpFile . exists ( ) ) { tmpFile . delete ( ) ; } } } | Saves the keystore to the specified file . |
5,931 | public static X509Certificate getCertificate ( String alias , File storeFile , String storePassword ) { try { KeyStore store = openKeyStore ( storeFile , storePassword ) ; X509Certificate caCert = ( X509Certificate ) store . getCertificate ( alias ) ; return caCert ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Retrieves the X509 certificate with the specified alias from the certificate store . |
5,932 | public static PrivateKey getPrivateKey ( String alias , File storeFile , String storePassword ) { try { KeyStore store = openKeyStore ( storeFile , storePassword ) ; PrivateKey key = ( PrivateKey ) store . getKey ( alias , storePassword . toCharArray ( ) ) ; return key ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Retrieves the private key for the specified alias from the certificate store . |
5,933 | public static void saveCertificate ( X509Certificate cert , File targetFile ) { File folder = targetFile . getAbsoluteFile ( ) . getParentFile ( ) ; if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } File tmpFile = new File ( folder , Long . toHexString ( System . currentTimeMillis ( ) ) + ".tmp" ) ; try { boolean asPem = targetFile . getName ( ) . toLowerCase ( ) . endsWith ( ".pem" ) ; if ( asPem ) { PEMWriter pemWriter = null ; try { pemWriter = new PEMWriter ( new FileWriter ( tmpFile ) ) ; pemWriter . writeObject ( cert ) ; pemWriter . flush ( ) ; } finally { if ( pemWriter != null ) { pemWriter . close ( ) ; } } } else { FileOutputStream fos = null ; try { fos = new FileOutputStream ( tmpFile ) ; fos . write ( cert . getEncoded ( ) ) ; fos . flush ( ) ; } finally { if ( fos != null ) { fos . close ( ) ; } } } if ( targetFile . exists ( ) ) { targetFile . delete ( ) ; } tmpFile . renameTo ( targetFile ) ; } catch ( Exception e ) { if ( tmpFile . exists ( ) ) { tmpFile . delete ( ) ; } throw new RuntimeException ( "Failed to save certificate " + cert . getSubjectX500Principal ( ) . getName ( ) , e ) ; } } | Saves the certificate to the file system . If the destination filename ends with the pem extension the certificate is written in the PEM format otherwise the certificate is written in the DER format . |
5,934 | private static KeyPair newKeyPair ( ) throws Exception { KeyPairGenerator kpGen = KeyPairGenerator . getInstance ( KEY_ALGORITHM , BC ) ; kpGen . initialize ( KEY_LENGTH , new SecureRandom ( ) ) ; return kpGen . generateKeyPair ( ) ; } | Generate a new keypair . |
5,935 | private static X500Name buildDistinguishedName ( X509Metadata metadata ) { X500NameBuilder dnBuilder = new X500NameBuilder ( BCStyle . INSTANCE ) ; setOID ( dnBuilder , metadata , "C" , null ) ; setOID ( dnBuilder , metadata , "ST" , null ) ; setOID ( dnBuilder , metadata , "L" , null ) ; setOID ( dnBuilder , metadata , "O" , "Fathom" ) ; setOID ( dnBuilder , metadata , "OU" , "Fathom" ) ; setOID ( dnBuilder , metadata , "E" , metadata . emailAddress ) ; setOID ( dnBuilder , metadata , "CN" , metadata . commonName ) ; X500Name dn = dnBuilder . build ( ) ; return dn ; } | Builds a distinguished name from the X509Metadata . |
5,936 | public static X509Certificate newSSLCertificate ( X509Metadata sslMetadata , PrivateKey caPrivateKey , X509Certificate caCert , File targetStoreFile , X509Log x509log ) { try { KeyPair pair = newKeyPair ( ) ; X500Name webDN = buildDistinguishedName ( sslMetadata ) ; X500Name issuerDN = new X500Name ( PrincipalUtil . getIssuerX509Principal ( caCert ) . getName ( ) ) ; X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder ( issuerDN , BigInteger . valueOf ( System . currentTimeMillis ( ) ) , sslMetadata . notBefore , sslMetadata . notAfter , webDN , pair . getPublic ( ) ) ; JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils ( ) ; certBuilder . addExtension ( X509Extension . subjectKeyIdentifier , false , extUtils . createSubjectKeyIdentifier ( pair . getPublic ( ) ) ) ; certBuilder . addExtension ( X509Extension . basicConstraints , false , new BasicConstraints ( false ) ) ; certBuilder . addExtension ( X509Extension . authorityKeyIdentifier , false , extUtils . createAuthorityKeyIdentifier ( caCert . getPublicKey ( ) ) ) ; List < GeneralName > altNames = new ArrayList < GeneralName > ( ) ; if ( isIpAddress ( sslMetadata . commonName ) ) { altNames . add ( new GeneralName ( GeneralName . iPAddress , sslMetadata . commonName ) ) ; } if ( altNames . size ( ) > 0 ) { GeneralNames subjectAltName = new GeneralNames ( altNames . toArray ( new GeneralName [ altNames . size ( ) ] ) ) ; certBuilder . addExtension ( X509Extension . subjectAlternativeName , false , subjectAltName ) ; } ContentSigner caSigner = new JcaContentSignerBuilder ( SIGNING_ALGORITHM ) . setProvider ( BC ) . build ( caPrivateKey ) ; X509Certificate cert = new JcaX509CertificateConverter ( ) . setProvider ( BC ) . getCertificate ( certBuilder . build ( caSigner ) ) ; cert . checkValidity ( new Date ( ) ) ; cert . verify ( caCert . getPublicKey ( ) ) ; KeyStore serverStore = openKeyStore ( targetStoreFile , sslMetadata . password ) ; serverStore . setKeyEntry ( sslMetadata . commonName , pair . getPrivate ( ) , sslMetadata . password . toCharArray ( ) , new Certificate [ ] { cert , caCert } ) ; saveKeyStore ( targetStoreFile , serverStore , sslMetadata . password ) ; x509log . log ( MessageFormat . format ( "New SSL certificate {0,number,0} [{1}]" , cert . getSerialNumber ( ) , cert . getSubjectDN ( ) . getName ( ) ) ) ; sslMetadata . serialNumber = cert . getSerialNumber ( ) . toString ( ) ; return cert ; } catch ( Throwable t ) { throw new RuntimeException ( "Failed to generate SSL certificate!" , t ) ; } } | Creates a new SSL certificate signed by the CA private key and stored in keyStore . |
5,937 | public static void addTrustedCertificate ( String alias , X509Certificate cert , File storeFile , String storePassword ) { try { KeyStore store = openKeyStore ( storeFile , storePassword ) ; store . setCertificateEntry ( alias , cert ) ; saveKeyStore ( storeFile , store , storePassword ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to import certificate into trust store " + storeFile , e ) ; } } | Imports a certificate into the trust store . |
5,938 | public static PKIXCertPathBuilderResult verifyChain ( X509Certificate testCert , X509Certificate ... additionalCerts ) { try { if ( isSelfSigned ( testCert ) ) { throw new RuntimeException ( "The certificate is self-signed. Nothing to verify." ) ; } Set < X509Certificate > certs = new HashSet < X509Certificate > ( ) ; certs . add ( testCert ) ; certs . addAll ( Arrays . asList ( additionalCerts ) ) ; X509CertSelector selector = new X509CertSelector ( ) ; selector . setCertificate ( testCert ) ; Set < TrustAnchor > trustAnchors = new HashSet < TrustAnchor > ( ) ; for ( X509Certificate cert : additionalCerts ) { if ( isSelfSigned ( cert ) ) { trustAnchors . add ( new TrustAnchor ( cert , null ) ) ; } } PKIXBuilderParameters pkixParams = new PKIXBuilderParameters ( trustAnchors , selector ) ; pkixParams . setRevocationEnabled ( false ) ; pkixParams . addCertStore ( CertStore . getInstance ( "Collection" , new CollectionCertStoreParameters ( certs ) , BC ) ) ; CertPathBuilder builder = CertPathBuilder . getInstance ( "PKIX" , BC ) ; PKIXCertPathBuilderResult verifiedCertChain = ( PKIXCertPathBuilderResult ) builder . build ( pkixParams ) ; return verifiedCertChain ; } catch ( CertPathBuilderException e ) { throw new RuntimeException ( "Error building certification path: " + testCert . getSubjectX500Principal ( ) , e ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error verifying the certificate: " + testCert . getSubjectX500Principal ( ) , e ) ; } } | Verifies a certificate s chain to ensure that it will function properly . |
5,939 | public static boolean isSelfSigned ( X509Certificate cert ) { try { cert . verify ( cert . getPublicKey ( ) ) ; return true ; } catch ( SignatureException e ) { return false ; } catch ( InvalidKeyException e ) { return false ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Checks whether given X . 509 certificate is self - signed . |
5,940 | protected boolean validatePassword ( StandardCredentials requestCredentials , StandardCredentials storedCredentials ) { final String storedPassword = storedCredentials . getPassword ( ) ; final String username = requestCredentials . getUsername ( ) ; final String password = requestCredentials . getPassword ( ) ; boolean authenticated = false ; if ( storedPassword . startsWith ( "$apr1$" ) ) { if ( storedPassword . equals ( Md5Crypt . apr1Crypt ( password , storedPassword ) ) ) { log . trace ( "Apache MD5 encoded password matched for user '{}'" , username ) ; authenticated = true ; } } else if ( storedPassword . startsWith ( "{SHA}" ) ) { String password64 = Base64 . encodeBase64String ( DigestUtils . sha1 ( password ) ) ; if ( storedPassword . substring ( "{SHA}" . length ( ) ) . equals ( password64 ) ) { log . trace ( "Unsalted SHA-1 encoded password matched for user '{}'" , username ) ; authenticated = true ; } } else if ( ! isAllowClearTextPasswords ( ) && storedPassword . equals ( Crypt . crypt ( password , storedPassword ) ) ) { log . trace ( "Libc crypt encoded password matched for user '{}'" , username ) ; authenticated = true ; } else if ( isAllowClearTextPasswords ( ) && storedPassword . equals ( password ) ) { log . trace ( "Clear text password matched for user '{}'" , username ) ; authenticated = true ; } return authenticated ; } | htpasswd supports a few other password encryption schemes than the StandardCredentialsRealm . |
5,941 | protected synchronized void readCredentialsFile ( ) { if ( realmFile != null && realmFile . exists ( ) && ( realmFile . lastModified ( ) != lastModified ) ) { lastModified = realmFile . lastModified ( ) ; try { Map < String , String > credentials = readCredentialsURL ( realmFile . toURI ( ) . toURL ( ) ) ; credentialsMap . clear ( ) ; credentialsMap . putAll ( credentials ) ; } catch ( Exception e ) { log . error ( "Failed to read {}" , realmFile , e ) ; } } } | Reads the credentials file and rebuilds the in - memory lookup tables . |
5,942 | protected Map < String , String > readCredentialsURL ( URL url ) { Map < String , String > credentials = new HashMap < > ( ) ; Pattern entry = Pattern . compile ( "^([^:]+):(.+)" ) ; try ( Scanner scanner = new Scanner ( url . openStream ( ) , StandardCharsets . UTF_8 . name ( ) ) ) { while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) . trim ( ) ; if ( ! line . isEmpty ( ) && ! line . startsWith ( "#" ) ) { Matcher m = entry . matcher ( line ) ; if ( m . matches ( ) ) { String username = m . group ( 1 ) ; String password = m . group ( 2 ) ; if ( Strings . isNullOrEmpty ( username ) ) { log . warn ( "Skipping line because the username is blank!" ) ; continue ; } if ( Strings . isNullOrEmpty ( password ) ) { log . warn ( "Skipping '{}' account because the password is blank!" , username ) ; continue ; } credentials . put ( username . trim ( ) , password . trim ( ) ) ; } } } } catch ( Exception e ) { log . error ( "Failed to read {}" , url , e ) ; } return credentials ; } | Reads the credentials url . |
5,943 | public Boot addShutdownHook ( ) { Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { Boot . this . stop ( ) ; } } ) ; return this ; } | Add a JVM shutdown hook . |
5,944 | public synchronized void start ( ) { Preconditions . checkNotNull ( getServer ( ) ) ; String osName = System . getProperty ( "os.name" ) ; String osVersion = System . getProperty ( "os.version" ) ; log . info ( "Bootstrapping {} ({})" , settings . getApplicationName ( ) , settings . getApplicationVersion ( ) ) ; Util . logSetting ( log , "Fathom" , Constants . getVersion ( ) ) ; Util . logSetting ( log , "Mode" , settings . getMode ( ) . toString ( ) ) ; Util . logSetting ( log , "Operating System" , String . format ( "%s (%s)" , osName , osVersion ) ) ; Util . logSetting ( log , "Available processors" , Runtime . getRuntime ( ) . availableProcessors ( ) ) ; Util . logSetting ( log , "Available heap" , ( Runtime . getRuntime ( ) . maxMemory ( ) / ( 1024 * 1024 ) ) + " MB" ) ; SimpleDateFormat df = new SimpleDateFormat ( "z Z" ) ; df . setTimeZone ( TimeZone . getDefault ( ) ) ; String offset = df . format ( new Date ( ) ) ; Util . logSetting ( log , "JVM timezone" , String . format ( "%s (%s)" , TimeZone . getDefault ( ) . getID ( ) , offset ) ) ; Util . logSetting ( log , "JVM locale" , Locale . getDefault ( ) ) ; long startTime = System . nanoTime ( ) ; getServer ( ) . start ( ) ; String contextPath = settings . getContextPath ( ) ; if ( settings . getHttpsPort ( ) > 0 ) { log . info ( "https://{}:{}{}" , settings . getHttpsListenAddress ( ) , settings . getHttpsPort ( ) , contextPath ) ; } if ( settings . getHttpPort ( ) > 0 ) { log . info ( "http://{}:{}{}" , settings . getHttpListenAddress ( ) , settings . getHttpPort ( ) , contextPath ) ; } if ( settings . getAjpPort ( ) > 0 ) { log . info ( "ajp://{}:{}{}" , settings . getAjpListenAddress ( ) , settings . getAjpPort ( ) , contextPath ) ; } long delta = TimeUnit . NANOSECONDS . toMillis ( System . nanoTime ( ) - startTime ) ; String duration ; if ( delta < 1000L ) { duration = String . format ( "%s ms" , delta ) ; } else { duration = String . format ( "%.1f seconds" , ( delta / 1000f ) ) ; } log . info ( "Fathom bootstrapped {} mode in {}" , settings . getMode ( ) . toString ( ) , duration ) ; log . info ( "READY." ) ; } | Starts Fathom synchronously . |
5,945 | public synchronized void stop ( ) { Preconditions . checkNotNull ( getServer ( ) ) ; if ( getServer ( ) . isRunning ( ) ) { try { log . info ( "Stopping..." ) ; getServer ( ) . stop ( ) ; log . info ( "STOPPED." ) ; } catch ( Exception e ) { Throwable t = Throwables . getRootCause ( e ) ; log . error ( "Fathom failed on shutdown!" , t ) ; } } } | Stops Fathom synchronously . |
5,946 | protected void setupLogback ( ) { if ( System . getProperty ( LOGBACK_CONFIGURATION_FILE_PROPERTY ) != null ) { return ; } URL configFileUrl = settings . getFileUrl ( LOGBACK_CONFIGURATION_FILE_PROPERTY , "classpath:conf/logback.xml" ) ; if ( configFileUrl == null ) { throw new FathomException ( "Failed to find Logback config file '{}'" , settings . getString ( LOGBACK_CONFIGURATION_FILE_PROPERTY , "classpath:conf/logback.xml" ) ) ; } LoggerContext context = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; try ( InputStream is = configFileUrl . openStream ( ) ) { JoranConfigurator configurator = new JoranConfigurator ( ) ; configurator . setContext ( context ) ; context . reset ( ) ; configurator . doConfigure ( is ) ; log . info ( "Configured Logback from '{}'" , configFileUrl ) ; } catch ( IOException | JoranException je ) { } StatusPrinter . printInCaseOfErrorsOrWarnings ( context ) ; } | Setup Logback logging by optionally reloading the configuration file . |
5,947 | public static AceRights parseValue ( final int value ) { final AceRights res = new AceRights ( ) ; if ( value == 0 ) { return res ; } res . others = value ; for ( ObjectRight type : ObjectRight . values ( ) ) { if ( ( value & type . getValue ( ) ) == type . getValue ( ) ) { res . rights . add ( type ) ; res . others ^= type . getValue ( ) ; } } return res ; } | Parse ACE rights . |
5,948 | public long asUInt ( ) { long res = others ; for ( ObjectRight right : rights ) { res += right . getValue ( ) ; } return res ; } | Gets rights as unsigned int . |
5,949 | public static String getParameterName ( Parameter parameter ) { String methodParameterName = parameter . getName ( ) ; if ( parameter . isAnnotationPresent ( Param . class ) ) { Param param = parameter . getAnnotation ( Param . class ) ; if ( ! Strings . isNullOrEmpty ( param . value ( ) ) ) { methodParameterName = param . value ( ) ; } } return methodParameterName ; } | Returns the name of a parameter . |
5,950 | public static Class < ? extends ArgumentExtractor > getArgumentExtractor ( Parameter parameter ) { for ( Annotation annotation : parameter . getAnnotations ( ) ) { if ( annotation . annotationType ( ) . isAnnotationPresent ( ExtractWith . class ) ) { ExtractWith with = annotation . annotationType ( ) . getAnnotation ( ExtractWith . class ) ; Class < ? extends ArgumentExtractor > extractorClass = with . value ( ) ; return extractorClass ; } } return ParamExtractor . class ; } | Returns the appropriate ArgumentExtractor to use for the controller method parameter . |
5,951 | public static QConnectorSync create ( final String host , final int port ) { return create ( host , port , true , true ) ; } | Reconnect on error and is thread - safe . |
5,952 | public static HtmlPlatform register ( Config config ) { HtmlPlatform platform = new HtmlPlatform ( config ) ; PlayN . setPlatform ( platform ) ; platform . init ( ) ; return platform ; } | Prepares the HTML platform for operation . |
5,953 | public GLShader prepareTexture ( int tex , int tint ) { if ( texEpoch != ctx . epoch ( ) ) { texCore = null ; } if ( texCore == null ) { createCore ( ) ; } boolean justActivated = ctx . useShader ( this ) ; if ( justActivated ) { texCore . activate ( ctx . curFbufWidth , ctx . curFbufHeight ) ; if ( GLContext . STATS_ENABLED ) ctx . stats . shaderBinds ++ ; } texCore . prepare ( tex , tint , justActivated ) ; return this ; } | Prepares this shader to render the specified texture etc . |
5,954 | public void addTriangles ( InternalTransform local , float [ ] xys , int xysOffset , int xysLen , float tw , float th , int [ ] indices , int indicesOffset , int indicesLen , int indexBase ) { texCore . addTriangles ( local . m00 ( ) , local . m01 ( ) , local . m10 ( ) , local . m11 ( ) , local . tx ( ) , local . ty ( ) , xys , xysOffset , xysLen , tw , th , indices , indicesOffset , indicesLen , indexBase ) ; if ( GLContext . STATS_ENABLED ) ctx . stats . trisRendered += indicesLen / 3 ; } | Adds a collection of triangles to the current render operation . |
5,955 | void willRotate ( UIInterfaceOrientation toOrient , double duration ) { if ( orientListener != null ) { orientListener . willRotate ( toOrient , duration ) ; } } | with iOS for rotation notifications game loop callbacks and app lifecycle events |
5,956 | private Touch . Event . Impl [ ] parseMotionEvent ( MotionEvent event , Events . Flags flags ) { int eventPointerCount = event . getPointerCount ( ) ; Touch . Event . Impl [ ] touches = new Touch . Event . Impl [ eventPointerCount ] ; double time = event . getEventTime ( ) ; float pressure , size ; int id ; for ( int t = 0 ; t < eventPointerCount ; t ++ ) { int pointerIndex = t ; IPoint xy = platform . graphics ( ) . transformTouch ( event . getX ( pointerIndex ) , event . getY ( pointerIndex ) ) ; pressure = event . getPressure ( pointerIndex ) ; size = event . getSize ( pointerIndex ) ; id = event . getPointerId ( pointerIndex ) ; touches [ t ] = new Touch . Event . Impl ( flags , time , xy . x ( ) , xy . y ( ) , id , pressure , size ) ; } return touches ; } | Performs the actual parsing of the MotionEvent event . |
5,957 | < L , E extends Input . Impl > void dispatch ( AbstractLayer layer , Class < L > listenerType , E event , Interaction < L , E > interaction ) { dispatch ( layer , listenerType , event , interaction , null ) ; } | Issues an interact call to a layer and listener with a localized copy of the given event . |
5,958 | public void setSize ( int pixelWidth , int pixelHeight , boolean fullscreen ) { setDisplayMode ( pixelWidth , pixelHeight , fullscreen ) ; ctx . setSize ( pixelWidth , pixelHeight ) ; } | Changes the size of the PlayN window . |
5,959 | public static void main ( String [ ] args ) { final PrintWriter out = new PrintWriter ( System . out ) ; final PrintWriter err = new PrintWriter ( System . err ) ; final int code = Launcher . main2 ( out , err , Arrays . asList ( args ) ) ; System . exit ( code ) ; } | Entry point from the operating system command line . |
5,960 | public void execute ( ) { try { Command command = new Parser ( ) . parse ( ) ; try { command . execute ( new ContextImpl ( ) , execute ) ; close ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error while executing command " + command , e ) ; } catch ( AssertionError e ) { throw new RuntimeException ( "Error while executing command " + command , e ) ; } } finally { try { reader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } writer . close ( ) ; try { close ( ) ; } catch ( SQLException e ) { } } } | Executes the commands from the input writing to the output then closing both input and output . |
5,961 | public boolean isProbablyDeterministic ( String sql ) { final String upperSql = sql . toUpperCase ( ) ; if ( ! upperSql . contains ( "ORDER BY" ) ) { return false ; } final int i = upperSql . lastIndexOf ( "ORDER BY" ) ; final String tail = upperSql . substring ( i ) ; final int closeCount = tail . length ( ) - tail . replace ( ")" , "" ) . length ( ) ; final int openCount = tail . length ( ) - tail . replace ( "(" , "" ) . length ( ) ; if ( closeCount > openCount ) { return false ; } return true ; } | Returns whether a SQL query is likely to produce results always in the same order . |
5,962 | private static String flush ( StringBuilder buf ) { final String s = buf . toString ( ) ; buf . setLength ( 0 ) ; return s ; } | Returns the contents of a StringBuilder and clears it for the next use . |
5,963 | protected int createPow2RepTex ( int width , int height , boolean repeatX , boolean repeatY , boolean mipmapped ) { int powtex = ctx . createTexture ( width , height , repeatX , repeatY , mipmapped ) ; updateTexture ( powtex ) ; return powtex ; } | Creates and populates a texture for use as our power - of - two texture . This is used when our main image data is already power - of - two - sized . |
5,964 | public static RSAPrivateKey getRSAPrivateKeyFromPEM ( Provider provider , String pem ) { try { KeyFactory keyFactory = KeyFactory . getInstance ( "RSA" , provider ) ; return ( RSAPrivateKey ) keyFactory . generatePrivate ( new PKCS8EncodedKeySpec ( getKeyBytesFromPEM ( pem ) ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( "Algorithm SHA256withRSA is not available" , e ) ; } catch ( InvalidKeySpecException e ) { throw new IllegalArgumentException ( "Invalid PEM provided" , e ) ; } } | Get an RSA private key utilizing the provided provider and PEM formatted string |
5,965 | public static RSAPublicKey getRSAPublicKeyFromPEM ( Provider provider , String pem ) { try { KeyFactory keyFactory = KeyFactory . getInstance ( "RSA" , provider ) ; return ( RSAPublicKey ) keyFactory . generatePublic ( new X509EncodedKeySpec ( getKeyBytesFromPEM ( pem ) ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( "Algorithm SHA256withRSA is not available" , e ) ; } catch ( InvalidKeySpecException e ) { throw new IllegalArgumentException ( "Invalid PEM provided" , e ) ; } } | Get an RSA public key utilizing the provided provider and PEM formatted string |
5,966 | public static String getPEMFromRSAPublicKey ( RSAPublicKey publicKey ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "-----BEGIN PUBLIC KEY-----\n" ) ; String encoded = new String ( BASE_64 . encode ( publicKey . getEncoded ( ) ) ) ; int start = 0 ; int end = 64 ; try { while ( true ) { builder . append ( encoded . substring ( start , end ) ) ; builder . append ( "\n" ) ; start = end ; end = start + 64 ; } } catch ( IndexOutOfBoundsException e ) { if ( start != encoded . length ( ) ) { builder . append ( encoded . substring ( start , encoded . length ( ) ) ) ; builder . append ( "\n" ) ; } } builder . append ( "-----END PUBLIC KEY-----\n" ) ; return builder . toString ( ) ; } | Get a PEM formatted string from the provided public key |
5,967 | public FactoryFactory build ( ) { return new FactoryFactory ( getJceProvider ( ) , getHttpClient ( ) , getKeyCache ( ) , getApiBaseURL ( ) , getApiIdentifier ( ) , getRequestExpireSeconds ( ) , offsetTTL , currentPublicKeyTTL , entityKeyMap ) ; } | Build a factory based on the currently configured information |
5,968 | private void throwQException ( final QConnectorException e ) { this . executor . execute ( new Runnable ( ) { public void run ( ) { QConnectorAsyncImpl . this . listener . exception ( e ) ; } } ) ; } | Throw an exception if something happened that the system can not fix . |
5,969 | private void throwQError ( final QConnectorError e ) { this . executor . execute ( new Runnable ( ) { public void run ( ) { QConnectorAsyncImpl . this . listener . error ( e ) ; } } ) ; } | Throw an error if something happened that the system can fix on his own but is might important to know . |
5,970 | private void throwResult ( final Result result ) { this . executor . execute ( new Runnable ( ) { public void run ( ) { QConnectorAsyncImpl . this . listener . resultReceived ( "" , result ) ; } } ) ; } | Throw result . |
5,971 | private int findChild ( L child , float depth ) { int startIdx = findInsertion ( depth ) ; for ( int ii = startIdx - 1 ; ii >= 0 ; ii -- ) { L c = children . get ( ii ) ; if ( c == child ) { return ii ; } if ( c . depth ( ) != depth ) { break ; } } for ( int ii = startIdx , ll = children . size ( ) ; ii < ll ; ii ++ ) { L c = children . get ( ii ) ; if ( c == child ) { return ii ; } if ( c . depth ( ) != depth ) { break ; } } return - 1 ; } | uses depth to improve upon a full linear search |
5,972 | private int findInsertion ( float depth ) { int low = 0 , high = children . size ( ) - 1 ; while ( low <= high ) { int mid = ( low + high ) >>> 1 ; float midDepth = children . get ( mid ) . depth ( ) ; if ( depth > midDepth ) { low = mid + 1 ; } else if ( depth < midDepth ) { high = mid - 1 ; } else { return mid ; } } return low ; } | who says you never have to write binary search? |
5,973 | void draw ( GLShader shader , InternalTransform xform , int tint , float dx , float dy , float dw , float dh ) { draw ( shader , xform , tint , dx , dy , dw , dh , 0 , 0 , ( repeatX ? dw : width ( ) ) , ( repeatY ? dh : height ( ) ) ) ; } | Draws this image with the supplied transform in the specified target dimensions . |
5,974 | void draw ( GLShader shader , InternalTransform xform , int tint , float dx , float dy , float dw , float dh , float sx , float sy , float sw , float sh ) { float texWidth = width ( ) , texHeight = height ( ) ; drawImpl ( shader , xform , ensureTexture ( ) , tint , dx , dy , dw , dh , sx / texWidth , sy / texHeight , ( sx + sw ) / texWidth , ( sy + sh ) / texHeight ) ; } | Draws this image with the supplied transform and source and target dimensions . |
5,975 | static int main2 ( PrintWriter out , PrintWriter err , List < String > args ) { try { final Launcher launcher = new Launcher ( args , out ) ; final Quidem quidem ; try { quidem = launcher . parse ( ) ; } catch ( ParseException e ) { return e . code ; } quidem . execute ( ) ; return 0 ; } catch ( Throwable e ) { out . flush ( ) ; e . printStackTrace ( err ) ; return 2 ; } finally { out . flush ( ) ; err . flush ( ) ; } } | Creates a launcher parses command line arguments and runs Quidem . |
5,976 | public void ellipsis ( String message ) { if ( length >= maxLength ) { try { out . write ( message ) ; out . flush ( ) ; } catch ( IOException e ) { throw Throwables . propagate ( e ) ; } } } | Appends a message if the limit has been reached or exceeded . |
5,977 | public void setSize ( int width , int height ) { rootElement . getStyle ( ) . setWidth ( width , Unit . PX ) ; rootElement . getStyle ( ) . setHeight ( height , Unit . PX ) ; } | Sizes or resizes the root element that contains the PlayN view . |
5,978 | public float uniformScale ( ) { float cp = m00 ( ) * m11 ( ) - m01 ( ) * m10 ( ) ; return ( cp < 0f ) ? - FloatMath . sqrt ( - cp ) : FloatMath . sqrt ( cp ) ; } | Pythagoras Transform implementation |
5,979 | private static GCHandle createHandle ( Buffer buffer ) { Object array ; if ( buffer instanceof ByteBuffer ) array = ( ( ByteBuffer ) buffer ) . array ( ) ; else if ( buffer instanceof ShortBuffer ) array = ( ( ShortBuffer ) buffer ) . array ( ) ; else if ( buffer instanceof IntBuffer ) array = ( ( IntBuffer ) buffer ) . array ( ) ; else if ( buffer instanceof FloatBuffer ) array = ( ( FloatBuffer ) buffer ) . array ( ) ; else if ( buffer instanceof DoubleBuffer ) array = ( ( DoubleBuffer ) buffer ) . array ( ) ; else throw new IllegalArgumentException ( ) ; return GCHandle . Alloc ( array , GCHandleType . wrap ( GCHandleType . Pinned ) ) ; } | Allocates a pinned GCHandle pointing at a buffer s data . Remember to free it! |
5,980 | public static < T > CallbackList < T > create ( Callback < T > callback ) { CallbackList < T > list = new CallbackList < T > ( ) ; list . add ( callback ) ; return list ; } | Creates a callback list populated with the supplied callback . |
5,981 | public CallbackList < T > add ( Callback < T > callback ) { checkState ( ) ; callbacks . add ( callback ) ; return this ; } | Adds the supplied callback to the list . |
5,982 | public void onSuccess ( T result ) { checkState ( ) ; for ( Callback < T > cb : callbacks ) { cb . onSuccess ( result ) ; } callbacks = null ; } | Dispatches success to all of the callbacks registered with this list . This may only be called once . |
5,983 | public void onFailure ( Throwable cause ) { checkState ( ) ; for ( Callback < T > cb : callbacks ) { cb . onFailure ( cause ) ; } callbacks = null ; } | Dispatches failure to all of the callbacks registered with this list . This may only be called once . |
5,984 | static void captureEvent ( final Element elem , String eventName , final EventHandler handler ) { HtmlPlatform . captureEvent ( elem , eventName , handler ) ; } | Capture events that occur on the target element only . |
5,985 | public static JavaPlatform register ( Config config ) { if ( config . headless && testInstance != null ) { return testInstance ; } JavaPlatform instance = new JavaPlatform ( config ) ; if ( config . headless ) { testInstance = instance ; } PlayN . setPlatform ( instance ) ; return instance ; } | Registers the Java platform with the specified configuration . |
5,986 | public synchronized Typeface get ( String name ) { Typeface typeface = mCache . get ( name ) ; if ( typeface == null ) { try { typeface = Typeface . createFromAsset ( mApplication . getAssets ( ) , name ) ; } catch ( Exception exp ) { return null ; } mCache . put ( name , typeface ) ; } return typeface ; } | If the cache has an instance for the typeface name this will return the instance immediately . Otherwise this method will create typeface instance and put it into the cache and return the instance . |
5,987 | public static synchronized TypefaceCache getInstance ( Context context ) { if ( sInstance == null ) sInstance = new TypefaceCache ( ( Application ) context . getApplicationContext ( ) ) ; return sInstance ; } | Retrieve this cache . |
5,988 | public static IOSPlatform register ( UIApplication app , Config config ) { return register ( app , null , config ) ; } | Registers your application using the supplied configuration . |
5,989 | public static IOSPlatform register ( UIApplication app , UIWindow window , Config config ) { IOSPlatform platform = new IOSPlatform ( app , window , config ) ; PlayN . setPlatform ( platform ) ; return platform ; } | Registers your application using the supplied configuration and window . |
5,990 | public boolean useShader ( GLShader shader ) { if ( curShader == shader ) return false ; checkGLError ( "useShader" ) ; flush ( true ) ; curShader = shader ; return true ; } | Makes the supplied shader the current shader flushing any previous shader . |
5,991 | private < L , E > void interact ( Class < L > type , Interaction < L , E > interaction , Interactor < ? > current , E argument ) { if ( current == null ) return ; interact ( type , interaction , current . next , argument ) ; if ( current . listenerType == type ) { @ SuppressWarnings ( "unchecked" ) L listener = ( L ) current . listener ; interaction . interact ( listener , argument ) ; } } | neither affects nor conflicts with the current dispatch |
5,992 | public int compareTo ( LongBuffer otherBuffer ) { int compareRemaining = ( remaining ( ) < otherBuffer . remaining ( ) ) ? remaining ( ) : otherBuffer . remaining ( ) ; int thisPos = position ; int otherPos = otherBuffer . position ; long thisLong , otherLong ; while ( compareRemaining > 0 ) { thisLong = get ( thisPos ) ; otherLong = otherBuffer . get ( otherPos ) ; if ( thisLong != otherLong ) { return thisLong < otherLong ? - 1 : 1 ; } thisPos ++ ; otherPos ++ ; compareRemaining -- ; } return remaining ( ) - otherBuffer . remaining ( ) ; } | Compare the remaining longs of this buffer to another long buffer s remaining longs . |
5,993 | public static Result convert ( final Object res ) throws QConnectorException { if ( res == null ) { return new EmptyResult ( ) ; } if ( res instanceof c . Flip ) { return new FlipResult ( "" , ( c . Flip ) res ) ; } if ( res instanceof c . Dict ) { final c . Dict dict = ( c . Dict ) res ; if ( ( dict . x instanceof c . Flip ) && ( dict . y instanceof c . Flip ) ) { final c . Flip key = ( c . Flip ) dict . x ; final c . Flip data = ( c . Flip ) dict . y ; return new FlipFlipResult ( "" , key , data ) ; } } if ( res instanceof Object [ ] ) { final Object [ ] oa = ( Object [ ] ) res ; if ( ( oa . length == 2 ) && ( oa [ 0 ] instanceof String ) && ( oa [ 1 ] instanceof c . Flip ) ) { final String table = ( String ) oa [ 0 ] ; final c . Flip flip = ( c . Flip ) oa [ 1 ] ; return new FlipResult ( table , flip ) ; } else if ( ( oa . length == 3 ) && ( oa [ 1 ] instanceof String ) && ( oa [ 2 ] instanceof c . Flip ) ) { final String table = ( String ) oa [ 1 ] ; final c . Flip flip = ( c . Flip ) oa [ 2 ] ; return new FlipResult ( table , flip ) ; } else { return new ListResult < Object > ( oa ) ; } } if ( res instanceof byte [ ] ) { return new ListResult < Byte > ( ArrayUtils . toObject ( ( byte [ ] ) res ) ) ; } } | Converts an result from the kx c library to a QConnector Result . |
5,994 | public void add ( Image image ) { assert ! start || listener == null ; ++ total ; image . addCallback ( callback ) ; } | Adds an image resource to be watched . |
5,995 | public void add ( Sound sound ) { assert ! start || listener == null ; ++ total ; sound . addCallback ( callback ) ; } | Adds a sound resource to be watched . |
5,996 | public static int nextPowerOfTwo ( int x ) { assert x < 0x10000 ; int bit = 0x8000 , highest = - 1 , count = 0 ; for ( int i = 15 ; i >= 0 ; -- i , bit >>= 1 ) { if ( ( x & bit ) != 0 ) { ++ count ; if ( highest == - 1 ) { highest = i ; } } } if ( count <= 1 ) { return 0 ; } return 1 << ( highest + 1 ) ; } | Returns the next largest power of two or zero if x is already a power of two . |
5,997 | public void setInline ( boolean value ) { inline = value ; if ( headingToggle != null ) { JQMCommon . setInlineEx ( headingToggle , value , JQMCommon . STYLE_UI_BTN_INLINE ) ; } } | Sets the header button as inline block . |
5,998 | public void setCollapsed ( boolean collapsed ) { if ( collapsed ) { removeAttribute ( "data-collapsed" ) ; if ( isInstance ( getElement ( ) ) ) collapse ( ) ; } else { setAttribute ( "data-collapsed" , "false" ) ; if ( isInstance ( getElement ( ) ) ) expand ( ) ; } } | Programmatically set the collapsed state of this widget . |
5,999 | public void setText ( String text ) { if ( headingToggle != null ) { if ( text == null ) text = "" ; String s = headingToggle . getInnerHTML ( ) ; int p = s . indexOf ( '<' ) ; if ( p >= 0 ) s = text + s . substring ( p ) ; else s = text ; headingToggle . setInnerHTML ( s ) ; } else if ( ! isInstance ( getElement ( ) ) ) { if ( headerPanel != null ) { super . remove ( headerPanel ) ; headerPanel = null ; } header . setText ( text ) ; } } | Sets the text on the header element |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.