idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
3,300
|
public String encrypt ( String data ) throws UnsupportedEncodingException , NoSuchAlgorithmException , NoSuchPaddingException , InvalidAlgorithmParameterException , InvalidKeyException , InvalidKeySpecException , BadPaddingException , IllegalBlockSizeException { if ( data == null ) return null ; SecretKey secretKey = getSecretKey ( hashTheKey ( mBuilder . getKey ( ) ) ) ; byte [ ] dataBytes = data . getBytes ( mBuilder . getCharsetName ( ) ) ; Cipher cipher = Cipher . getInstance ( mBuilder . getAlgorithm ( ) ) ; cipher . init ( Cipher . ENCRYPT_MODE , secretKey , mBuilder . getIvParameterSpec ( ) , mBuilder . getSecureRandom ( ) ) ; return Base64 . encodeToString ( cipher . doFinal ( dataBytes ) , mBuilder . getBase64Mode ( ) ) ; }
|
Encrypt a String
|
3,301
|
public void encryptAsync ( final String data , final Callback callback ) { if ( callback == null ) return ; new Thread ( new Runnable ( ) { public void run ( ) { try { String encrypt = encrypt ( data ) ; if ( encrypt == null ) { callback . onError ( new Exception ( "Encrypt return null, it normally occurs when you send a null data" ) ) ; } callback . onSuccess ( encrypt ) ; } catch ( Exception e ) { callback . onError ( e ) ; } } } ) . start ( ) ; }
|
This is a sugar method that calls encrypt method in background it is a good idea to use this one instead the default method because encryption can take several time and with this method the process occurs in a AsyncTask other advantage is the Callback with separated methods one for success and other for the exception
|
3,302
|
public String decrypt ( String data ) throws UnsupportedEncodingException , NoSuchAlgorithmException , InvalidKeySpecException , NoSuchPaddingException , InvalidAlgorithmParameterException , InvalidKeyException , BadPaddingException , IllegalBlockSizeException { if ( data == null ) return null ; byte [ ] dataBytes = Base64 . decode ( data , mBuilder . getBase64Mode ( ) ) ; SecretKey secretKey = getSecretKey ( hashTheKey ( mBuilder . getKey ( ) ) ) ; Cipher cipher = Cipher . getInstance ( mBuilder . getAlgorithm ( ) ) ; cipher . init ( Cipher . DECRYPT_MODE , secretKey , mBuilder . getIvParameterSpec ( ) , mBuilder . getSecureRandom ( ) ) ; byte [ ] dataBytesDecrypted = ( cipher . doFinal ( dataBytes ) ) ; return new String ( dataBytesDecrypted ) ; }
|
Decrypt a String
|
3,303
|
public void decryptAsync ( final String data , final Callback callback ) { if ( callback == null ) return ; new Thread ( new Runnable ( ) { public void run ( ) { try { String decrypt = decrypt ( data ) ; if ( decrypt == null ) { callback . onError ( new Exception ( "Decrypt return null, it normally occurs when you send a null data" ) ) ; } callback . onSuccess ( decrypt ) ; } catch ( Exception e ) { callback . onError ( e ) ; } } } ) . start ( ) ; }
|
This is a sugar method that calls decrypt method in background it is a good idea to use this one instead the default method because decryption can take several time and with this method the process occurs in a AsyncTask other advantage is the Callback with separated methods one for success and other for the exception
|
3,304
|
private SecretKey getSecretKey ( char [ ] key ) throws NoSuchAlgorithmException , UnsupportedEncodingException , InvalidKeySpecException { SecretKeyFactory factory = SecretKeyFactory . getInstance ( mBuilder . getSecretKeyType ( ) ) ; KeySpec spec = new PBEKeySpec ( key , mBuilder . getSalt ( ) . getBytes ( mBuilder . getCharsetName ( ) ) , mBuilder . getIterationCount ( ) , mBuilder . getKeyLength ( ) ) ; SecretKey tmp = factory . generateSecret ( spec ) ; return new SecretKeySpec ( tmp . getEncoded ( ) , mBuilder . getKeyAlgorithm ( ) ) ; }
|
creates a 128bit salted aes key
|
3,305
|
private char [ ] hashTheKey ( String key ) throws UnsupportedEncodingException , NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest . getInstance ( mBuilder . getDigestAlgorithm ( ) ) ; messageDigest . update ( key . getBytes ( mBuilder . getCharsetName ( ) ) ) ; return Base64 . encodeToString ( messageDigest . digest ( ) , Base64 . NO_PADDING ) . toCharArray ( ) ; }
|
takes in a simple string and performs an sha1 hash that is 128 bits long ... we then base64 encode it and return the char array
|
3,306
|
private void renderTag ( Tag tag , StringBuilder buffer ) { buffer . append ( tag . name ( ) ) . append ( ' ' ) ; if ( ( tag instanceof ParamTag ) && ( ( ParamTag ) tag ) . isTypeParameter ( ) ) { ParamTag paramTag = ( ParamTag ) tag ; buffer . append ( "<" + paramTag . parameterName ( ) + ">" ) ; String text = paramTag . parameterComment ( ) ; if ( text . length ( ) > 0 ) { buffer . append ( ' ' ) . append ( render ( text , true ) ) ; } return ; } buffer . append ( render ( tag . text ( ) , true ) ) ; }
|
Renders a document tag in the standard way .
|
3,307
|
private String render ( String input , boolean inline ) { if ( input . trim ( ) . isEmpty ( ) ) { return "" ; } options . setDocType ( inline ? INLINE_DOCTYPE : null ) ; return asciidoctor . render ( cleanJavadocInput ( input ) , options ) ; }
|
Renders the input using Asciidoctor .
|
3,308
|
@ SuppressWarnings ( "UnusedDeclaration" ) public static boolean validOptions ( String [ ] [ ] options , DocErrorReporter errorReporter ) { return validOptions ( options , errorReporter , new StandardAdapter ( ) ) ; }
|
Processes the input options by delegating to the standard handler .
|
3,309
|
public boolean render ( RootDoc rootDoc , DocletRenderer renderer ) { if ( ! processOverview ( rootDoc , renderer ) ) { return false ; } Set < PackageDoc > packages = new HashSet < PackageDoc > ( ) ; for ( ClassDoc doc : rootDoc . classes ( ) ) { packages . add ( doc . containingPackage ( ) ) ; renderClass ( doc , renderer ) ; } for ( PackageDoc doc : packages ) { renderer . renderDoc ( doc ) ; } return true ; }
|
Renders a RootDoc s contents .
|
3,310
|
private void renderClass ( ClassDoc doc , DocletRenderer renderer ) { renderer . renderDoc ( doc ) ; for ( MemberDoc member : doc . fields ( ) ) { renderer . renderDoc ( member ) ; } for ( MemberDoc member : doc . constructors ( ) ) { renderer . renderDoc ( member ) ; } for ( MemberDoc member : doc . methods ( ) ) { renderer . renderDoc ( member ) ; } for ( MemberDoc member : doc . enumConstants ( ) ) { renderer . renderDoc ( member ) ; } if ( doc instanceof AnnotationTypeDoc ) { for ( MemberDoc member : ( ( AnnotationTypeDoc ) doc ) . elements ( ) ) { renderer . renderDoc ( member ) ; } } }
|
Renders an individual class .
|
3,311
|
public void close ( ) throws IOException , GeneralSecurityException { if ( mManifest != null ) { mOutputJar . putNextEntry ( new JarEntry ( JarFile . MANIFEST_NAME ) ) ; mManifest . write ( mOutputJar ) ; Signature signature = Signature . getInstance ( "SHA1with" + mKey . getAlgorithm ( ) ) ; signature . initSign ( mKey ) ; mOutputJar . putNextEntry ( new JarEntry ( "META-INF/CERT.SF" ) ) ; SignatureOutputStream out = new SignatureOutputStream ( mOutputJar , signature ) ; writeSignatureFile ( out ) ; mOutputJar . putNextEntry ( new JarEntry ( "META-INF/CERT." + mKey . getAlgorithm ( ) ) ) ; writeSignatureBlock ( signature , mCertificate , mKey ) ; out . close ( ) ; } mOutputJar . close ( ) ; mOutputJar = null ; }
|
Closes the Jar archive by creating the manifest and signing the archive .
|
3,312
|
private void writeSignatureBlock ( Signature signature , X509Certificate publicKey , PrivateKey privateKey ) throws IOException , GeneralSecurityException { SignerInfo signerInfo = new SignerInfo ( new X500Name ( publicKey . getIssuerX500Principal ( ) . getName ( ) ) , publicKey . getSerialNumber ( ) , AlgorithmId . get ( DIGEST_ALGORITHM ) , AlgorithmId . get ( privateKey . getAlgorithm ( ) ) , signature . sign ( ) ) ; PKCS7 pkcs7 = new PKCS7 ( new AlgorithmId [ ] { AlgorithmId . get ( DIGEST_ALGORITHM ) } , new ContentInfo ( ContentInfo . DATA_OID , null ) , new X509Certificate [ ] { publicKey } , new SignerInfo [ ] { signerInfo } ) ; pkcs7 . encodeSignedData ( mOutputJar ) ; }
|
Write the certificate file with a digital signature .
|
3,313
|
public void validate ( ) { Revision revBuildToolsVersion = Revision . parseRevision ( buildToolsVersion ) ; if ( minimalBuildToolsVersion . compareTo ( revBuildToolsVersion ) > 0 ) { throw new GradleException ( "Android buildToolsVersion should be at least version " + minimalBuildToolsVersion + ": currently using " + buildToolsVersion + " from " + buildToolsDir + ". See https://developer.android.com/studio/intro/update.html on how to update the build tools in the Android SDK." ) ; } if ( ! project . file ( buildToolsDir + "/aapt" ) . exists ( ) && ! project . file ( buildToolsDir + "/aapt.exe" ) . exists ( ) ) { throw new GradleException ( "Configured buildToolsVersion is invalid: " + buildToolsVersion + " (" + buildToolsDir + ")" ) ; } if ( ! project . file ( androidSdk + "/platforms/android-" + compileSdkVersion ) . exists ( ) ) { throw new GradleException ( "Configured compileSdkVersion is invalid: " + compileSdkVersion + " (" + androidSdk + "/platforms/android-" + compileSdkVersion + ")" ) ; } sdkHandler . ensurePlatformToolsIsInstalled ( extraModelInfo ) ; }
|
Checks whether the properties on the android extension are valid after everything was configured .
|
3,314
|
public static SigningInfo getDebugKey ( String storeOsPath , final PrintStream verboseStream ) throws ApkCreationException { try { if ( storeOsPath != null ) { File storeFile = new File ( storeOsPath ) ; try { checkInputFile ( storeFile ) ; } catch ( FileNotFoundException e ) { } if ( verboseStream != null ) { verboseStream . println ( String . format ( "Using keystore: %s" , storeOsPath ) ) ; } IKeyGenOutput keygenOutput = null ; if ( verboseStream != null ) { keygenOutput = new IKeyGenOutput ( ) { public void out ( String message ) { verboseStream . println ( message ) ; } public void err ( String message ) { verboseStream . println ( message ) ; } } ; } DebugKeyProvider keyProvider = new DebugKeyProvider ( storeOsPath , null , keygenOutput ) ; PrivateKey key = keyProvider . getDebugKey ( ) ; X509Certificate certificate = ( X509Certificate ) keyProvider . getCertificate ( ) ; if ( key == null ) { throw new ApkCreationException ( "Unable to get debug signature key" ) ; } if ( certificate != null && certificate . getNotAfter ( ) . compareTo ( new Date ( ) ) < 0 ) { throw new ApkCreationException ( "Debug Certificate expired on " + DateFormat . getInstance ( ) . format ( certificate . getNotAfter ( ) ) ) ; } return new SigningInfo ( key , certificate ) ; } else { return null ; } } catch ( KeytoolException e ) { if ( e . getJavaHome ( ) == null ) { throw new ApkCreationException ( e . getMessage ( ) + "\nJAVA_HOME seems undefined, setting it will help locating keytool automatically\n" + "You can also manually execute the following command\n:" + e . getCommandLine ( ) , e ) ; } else { throw new ApkCreationException ( e . getMessage ( ) + "\nJAVA_HOME is set to: " + e . getJavaHome ( ) + "\nUpdate it if necessary, or manually execute the following command:\n" + e . getCommandLine ( ) , e ) ; } } catch ( ApkCreationException e ) { throw e ; } catch ( Exception e ) { throw new ApkCreationException ( e ) ; } }
|
Returns the key and certificate from a given debug store .
|
3,315
|
private void init ( File apkFile , File resFile , File dexFile , PrivateKey key , X509Certificate certificate , PrintStream verboseStream ) throws ApkCreationException { try { checkOutputFile ( mApkFile = apkFile ) ; checkInputFile ( mResFile = resFile ) ; if ( dexFile != null ) { checkInputFile ( mDexFile = dexFile ) ; } else { mDexFile = null ; } mVerboseStream = verboseStream ; mBuilder = new SignedJarBuilder ( new FileOutputStream ( mApkFile , false ) , key , certificate ) ; verbosePrintln ( "Packaging %s" , mApkFile . getName ( ) ) ; addZipFile ( mResFile ) ; if ( mDexFile != null ) { addFile ( mDexFile , SdkConstants . FN_APK_CLASSES_DEX ) ; } } catch ( ApkCreationException e ) { if ( mBuilder != null ) { mBuilder . cleanUp ( ) ; } throw e ; } catch ( Exception e ) { if ( mBuilder != null ) { mBuilder . cleanUp ( ) ; } throw new ApkCreationException ( e ) ; } }
|
Constructor init method .
|
3,316
|
public void addFile ( File file , String archivePath ) throws ApkCreationException , SealedApkException , DuplicateFileException { if ( mIsSealed ) { throw new SealedApkException ( "APK is already sealed" ) ; } try { doAddFile ( file , archivePath ) ; } catch ( DuplicateFileException e ) { mBuilder . cleanUp ( ) ; throw e ; } catch ( Exception e ) { mBuilder . cleanUp ( ) ; throw new ApkCreationException ( e , "Failed to add %s" , file ) ; } }
|
Adds a file to the APK at a given path
|
3,317
|
public void addZipFile ( File zipFile ) throws ApkCreationException , SealedApkException , DuplicateFileException { if ( mIsSealed ) { throw new SealedApkException ( "APK is already sealed" ) ; } try { verbosePrintln ( "%s:" , zipFile ) ; mNullFilter . reset ( zipFile ) ; FileInputStream fis = new FileInputStream ( zipFile ) ; mBuilder . writeZip ( fis , mNullFilter ) ; fis . close ( ) ; } catch ( DuplicateFileException e ) { mBuilder . cleanUp ( ) ; throw e ; } catch ( Exception e ) { mBuilder . cleanUp ( ) ; throw new ApkCreationException ( e , "Failed to add %s" , zipFile ) ; } }
|
Adds the content from a zip file . All file keep the same path inside the archive .
|
3,318
|
public JarStatus addResourcesFromJar ( File jarFile ) throws ApkCreationException , SealedApkException , DuplicateFileException { if ( mIsSealed ) { throw new SealedApkException ( "APK is already sealed" ) ; } try { verbosePrintln ( "%s:" , jarFile ) ; mFilter . reset ( jarFile ) ; FileInputStream fis = new FileInputStream ( jarFile ) ; mBuilder . writeZip ( fis , mFilter ) ; fis . close ( ) ; return new JarStatusImpl ( mFilter . getNativeLibs ( ) , mFilter . getNativeLibsConflict ( ) ) ; } catch ( DuplicateFileException e ) { mBuilder . cleanUp ( ) ; throw e ; } catch ( Exception e ) { mBuilder . cleanUp ( ) ; throw new ApkCreationException ( e , "Failed to add %s" , jarFile ) ; } }
|
Adds the resources from a jar file .
|
3,319
|
public void addSourceFolder ( File sourceFolder ) throws ApkCreationException , SealedApkException , DuplicateFileException { if ( mIsSealed ) { throw new SealedApkException ( "APK is already sealed" ) ; } addSourceFolder ( this , sourceFolder ) ; }
|
Adds the resources from a source folder .
|
3,320
|
public void addNativeLibraries ( File nativeFolder ) throws ApkCreationException , SealedApkException , DuplicateFileException { if ( mIsSealed ) { throw new SealedApkException ( "APK is already sealed" ) ; } if ( ! nativeFolder . isDirectory ( ) ) { if ( nativeFolder . exists ( ) ) { throw new ApkCreationException ( "%s is not a folder" , nativeFolder ) ; } else { throw new ApkCreationException ( "%s does not exist" , nativeFolder ) ; } } File [ ] abiList = nativeFolder . listFiles ( ) ; verbosePrintln ( "Native folder: %s" , nativeFolder ) ; if ( abiList != null ) { for ( File abi : abiList ) { if ( abi . isDirectory ( ) ) { File [ ] libs = abi . listFiles ( ) ; if ( libs != null ) { for ( File lib : libs ) { if ( lib . isFile ( ) && ( PATTERN_NATIVELIB_EXT . matcher ( lib . getName ( ) ) . matches ( ) || PATTERN_BITCODELIB_EXT . matcher ( lib . getName ( ) ) . matches ( ) || ( mDebugMode && SdkConstants . FN_GDBSERVER . equals ( lib . getName ( ) ) ) ) ) { String path = SdkConstants . FD_APK_NATIVE_LIBS + "/" + abi . getName ( ) + "/" + lib . getName ( ) ; try { doAddFile ( lib , path ) ; } catch ( IOException e ) { mBuilder . cleanUp ( ) ; throw new ApkCreationException ( e , "Failed to add %s" , lib ) ; } } } } } } } }
|
Adds the native libraries from the top native folder . The content of this folder must be the various ABI folders .
|
3,321
|
public void sealApk ( ) throws ApkCreationException , SealedApkException { if ( mIsSealed ) { throw new SealedApkException ( "APK is already sealed" ) ; } try { mBuilder . close ( ) ; mIsSealed = true ; } catch ( Exception e ) { throw new ApkCreationException ( e , "Failed to seal APK" ) ; } finally { mBuilder . cleanUp ( ) ; } }
|
Seals the APK and signs it if necessary .
|
3,322
|
private void verbosePrintln ( String format , Object ... args ) { if ( mVerboseStream != null ) { mVerboseStream . println ( String . format ( format , args ) ) ; } }
|
Output a given message if the verbose mode is enabled .
|
3,323
|
public static boolean checkFolderForPackaging ( String folderName ) { return ! folderName . equalsIgnoreCase ( "CVS" ) && ! folderName . equalsIgnoreCase ( ".svn" ) && ! folderName . equalsIgnoreCase ( "SCCS" ) && ! folderName . startsWith ( "_" ) ; }
|
Checks whether a folder and its content is valid for packaging into the . apk as standard Java resource .
|
3,324
|
public void applyConfiguration ( Configuration configuration ) { if ( plugins != null ) { plugins . stream ( ) . filter ( pluginDefinition -> pluginDefinition . isConfigurationSupported ( configuration ) ) . forEach ( pluginDefinition -> project . getDependencies ( ) . add ( configuration . getName ( ) , generateDependencyNotation ( configuration , pluginDefinition ) ) ) ; } }
|
Add dependencies to the specified configuration . Only dependencies to plugins that support the provided configuration will be included .
|
3,325
|
List < ResourceSet > computeResourceSetList ( ) { List < ResourceSet > sourceFolderSets = resSetSupplier . get ( ) ; int size = sourceFolderSets . size ( ) + 4 ; if ( libraries != null ) { size += libraries . getArtifacts ( ) . size ( ) ; } List < ResourceSet > resourceSetList = Lists . newArrayListWithExpectedSize ( size ) ; if ( libraries != null ) { Set < ResolvedArtifactResult > libArtifacts = libraries . getArtifacts ( ) ; for ( ResolvedArtifactResult artifact : libArtifacts ) { ResourceSet resourceSet = new ResourceSet ( MergeManifests . getArtifactName ( artifact ) , null , null , validateEnabled ) ; resourceSet . setFromDependency ( true ) ; resourceSet . addSource ( artifact . getFile ( ) ) ; resourceSetList . add ( 0 , resourceSet ) ; } } resourceSetList . addAll ( sourceFolderSets ) ; List < File > generatedResFolders = Lists . newArrayList ( ) ; generatedResFolders . addAll ( renderscriptResOutputDir . getFiles ( ) ) ; generatedResFolders . addAll ( generatedResOutputDir . getFiles ( ) ) ; final ResourceSet mainResourceSet = sourceFolderSets . get ( 0 ) ; assert mainResourceSet . getConfigName ( ) . equals ( BuilderConstants . MAIN ) ; mainResourceSet . addSources ( generatedResFolders ) ; return resourceSetList ; }
|
Compute the list of resource set to be used during execution based all the inputs .
|
3,326
|
private static void examineAsBrowser ( final UserAgent . Builder builder , final Data data ) { Matcher matcher ; VersionNumber version = VersionNumber . UNKNOWN ; for ( final Entry < BrowserPattern , Browser > entry : data . getPatternToBrowserMap ( ) . entrySet ( ) ) { matcher = entry . getKey ( ) . getPattern ( ) . matcher ( builder . getUserAgentString ( ) ) ; if ( matcher . find ( ) ) { entry . getValue ( ) . copyTo ( builder ) ; if ( matcher . groupCount ( ) > ZERO_MATCHING_GROUPS ) { version = VersionNumber . parseVersion ( matcher . group ( 1 ) != null ? matcher . group ( 1 ) : "" ) ; } builder . setVersionNumber ( version ) ; break ; } } }
|
Examines the user agent string whether it is a browser .
|
3,327
|
private static boolean examineAsRobot ( final UserAgent . Builder builder , final Data data ) { boolean isRobot = false ; VersionNumber version ; for ( final Robot robot : data . getRobots ( ) ) { if ( robot . getUserAgentString ( ) . equals ( builder . getUserAgentString ( ) ) ) { isRobot = true ; robot . copyTo ( builder ) ; version = VersionNumber . parseLastVersionNumber ( robot . getName ( ) ) ; builder . setVersionNumber ( version ) ; break ; } } return isRobot ; }
|
Examines the user agent string whether it is a robot .
|
3,328
|
private static void examineDeviceCategory ( final UserAgent . Builder builder , final Data data ) { if ( UserAgentType . ROBOT == builder . getType ( ) ) { final DeviceCategory category = findDeviceCategoryByValue ( Category . OTHER , data ) ; builder . setDeviceCategory ( category ) ; return ; } for ( final Entry < DevicePattern , Device > entry : data . getPatternToDeviceMap ( ) . entrySet ( ) ) { final Matcher matcher = entry . getKey ( ) . getPattern ( ) . matcher ( builder . getUserAgentString ( ) ) ; if ( matcher . find ( ) ) { final Category category = Category . evaluate ( entry . getValue ( ) . getName ( ) ) ; final DeviceCategory deviceCategory = findDeviceCategoryByValue ( category , data ) ; builder . setDeviceCategory ( deviceCategory ) ; return ; } } if ( UserAgentType . UNKNOWN == builder . getType ( ) ) { builder . setDeviceCategory ( DeviceCategory . EMPTY ) ; return ; } if ( UserAgentType . OTHER == builder . getType ( ) || UserAgentType . LIBRARY == builder . getType ( ) || UserAgentType . VALIDATOR == builder . getType ( ) || UserAgentType . USERAGENT_ANONYMIZER == builder . getType ( ) ) { final DeviceCategory category = findDeviceCategoryByValue ( Category . OTHER , data ) ; builder . setDeviceCategory ( category ) ; return ; } if ( UserAgentType . MOBILE_BROWSER == builder . getType ( ) || UserAgentType . WAP_BROWSER == builder . getType ( ) ) { final DeviceCategory category = findDeviceCategoryByValue ( Category . SMARTPHONE , data ) ; builder . setDeviceCategory ( category ) ; return ; } final DeviceCategory category = findDeviceCategoryByValue ( Category . PERSONAL_COMPUTER , data ) ; builder . setDeviceCategory ( category ) ; }
|
Examines the user agent string whether has a specific device category .
|
3,329
|
private static void examineOperatingSystem ( final UserAgent . Builder builder , final Data data ) { if ( net . sf . uadetector . OperatingSystem . EMPTY . equals ( builder . getOperatingSystem ( ) ) ) { for ( final Entry < OperatingSystemPattern , OperatingSystem > entry : data . getPatternToOperatingSystemMap ( ) . entrySet ( ) ) { final Matcher matcher = entry . getKey ( ) . getPattern ( ) . matcher ( builder . getUserAgentString ( ) ) ; if ( matcher . find ( ) ) { entry . getValue ( ) . copyTo ( builder ) ; break ; } } } }
|
Examines the operating system of the user agent string if not available .
|
3,330
|
public int compare ( final T o1 , final T o2 ) { int result = 0 ; if ( o1 == null ) { if ( o2 != null ) { result = - 1 ; } } else if ( o2 == null ) { result = 1 ; } else { result = compareType ( o1 , o2 ) ; } return result ; }
|
Compares two objects null safe to each other .
|
3,331
|
private static int compareInt ( final int a , final int b ) { int result = 0 ; if ( a > b ) { result = 1 ; } else if ( a < b ) { result = - 1 ; } return result ; }
|
Compares to integers .
|
3,332
|
static boolean hasUpdate ( final String newer , final String older ) { return VERSION_PATTERN . matcher ( newer ) . matches ( ) && VERSION_PATTERN . matcher ( older ) . matches ( ) ? newer . compareTo ( older ) > 0 : false ; }
|
Checks a given newer version against an older one .
|
3,333
|
protected boolean isUpdateAvailable ( ) { boolean result = false ; String version = EMPTY_VERSION ; try { version = retrieveRemoteVersion ( store . getVersionUrl ( ) , store . getCharset ( ) ) ; } catch ( final IOException e ) { LOG . info ( MSG_NO_UPDATE_CHECK_POSSIBLE ) ; LOG . debug ( String . format ( MSG_NO_UPDATE_CHECK_POSSIBLE__DEBUG , e . getClass ( ) . getName ( ) , e . getLocalizedMessage ( ) ) ) ; } if ( hasUpdate ( version , getCurrentVersion ( ) ) ) { LOG . debug ( String . format ( MSG_UPDATE_AVAILABLE , getCurrentVersion ( ) , version ) ) ; result = true ; } else { LOG . debug ( String . format ( MSG_NO_UPDATE_AVAILABLE , getCurrentVersion ( ) ) ) ; } lastUpdateCheck = System . currentTimeMillis ( ) ; return result ; }
|
Fetches the current version information over HTTP and compares it with the last version of the most recently imported data .
|
3,334
|
public DataBuilder appendBrowserPattern ( final BrowserPattern pattern ) { Check . notNull ( pattern , "pattern" ) ; if ( ! browserPatterns . containsKey ( pattern . getId ( ) ) ) { browserPatterns . put ( pattern . getId ( ) , new TreeSet < BrowserPattern > ( BROWSER_PATTERN_COMPARATOR ) ) ; } browserPatterns . get ( pattern . getId ( ) ) . add ( pattern ) ; return this ; }
|
Appends a browser pattern to the map of pattern sorted by ID .
|
3,335
|
public DataBuilder appendDevicePattern ( final DevicePattern pattern ) { Check . notNull ( pattern , "pattern" ) ; if ( ! devicePatterns . containsKey ( pattern . getId ( ) ) ) { devicePatterns . put ( pattern . getId ( ) , new TreeSet < DevicePattern > ( DEVICE_PATTERN_COMPARATOR ) ) ; } devicePatterns . get ( pattern . getId ( ) ) . add ( pattern ) ; return this ; }
|
Appends a device pattern to the map of pattern sorted by ID .
|
3,336
|
public DataBuilder appendOperatingSystemPattern ( final OperatingSystemPattern pattern ) { Check . notNull ( pattern , "pattern" ) ; if ( ! operatingSystemPatterns . containsKey ( pattern . getId ( ) ) ) { operatingSystemPatterns . put ( pattern . getId ( ) , new TreeSet < OperatingSystemPattern > ( OS_PATTERN_COMPARATOR ) ) ; } operatingSystemPatterns . get ( pattern . getId ( ) ) . add ( pattern ) ; return this ; }
|
Appends an operating system pattern to the map of pattern sorted by ID .
|
3,337
|
private void setUpUpdateService ( ) { if ( currentUpdateTask != null ) { currentUpdateTask . cancel ( false ) ; } currentUpdateTask = scheduler . scheduleWithFixedDelay ( getDataStore ( ) . getUpdateOperation ( ) , 0 , updateInterval , MILLISECONDS ) ; }
|
Set up a new update service to get newer UAS data
|
3,338
|
public void copyTo ( final UserAgent . Builder builder ) { final OperatingSystemFamily f = OperatingSystemFamily . evaluate ( family ) ; final VersionNumber version = VersionNumber . parseOperatingSystemVersion ( f , builder . getUserAgentString ( ) ) ; builder . setOperatingSystem ( new net . sf . uadetector . OperatingSystem ( f , family , icon , name , producer , producerUrl , url , version ) ) ; }
|
Copies all information of the current operating system entry to the given user agent builder .
|
3,339
|
protected static File createTemporaryFile ( final File file ) { Check . notNull ( file , "file" ) ; final File tempFile = new File ( file . getParent ( ) , file . getName ( ) + ".temp" ) ; deleteFile ( tempFile ) ; return tempFile ; }
|
Creates a temporary file near the passed file . The name of the given one will be used and the suffix . temp will be added .
|
3,340
|
protected static void deleteFile ( final File file ) { Check . notNull ( file , "file" ) ; Check . stateIsTrue ( ! file . exists ( ) || file . delete ( ) , "Cannot delete file '%s'." , file . getPath ( ) ) ; }
|
Removes the given file .
|
3,341
|
private static String toVersionString ( final List < String > groups ) { final StringBuilder builder = new StringBuilder ( 6 ) ; int count = 0 ; for ( final String segment : groups ) { if ( EMPTY_GROUP . equals ( segment ) ) { break ; } else { if ( count > 0 ) { builder . append ( SEPARATOR ) ; } builder . append ( segment ) ; } count ++ ; } return builder . toString ( ) ; }
|
Converts the given list of numbers in a version string . The groups of the version number will be separated by a dot .
|
3,342
|
public int compareTo ( final ReadableVersionNumber other ) { int result = 0 ; if ( other == null ) { result = - 1 ; } else { Check . notNull ( other . getGroups ( ) , "other.getGroups()" ) ; final int length = groups . size ( ) < other . getGroups ( ) . size ( ) ? groups . size ( ) : other . getGroups ( ) . size ( ) ; final NaturalOrderComparator comparator = new NaturalOrderComparator ( ) ; result = comparator . compare ( toVersionString ( groups . subList ( 0 , length ) ) , toVersionString ( other . getGroups ( ) . subList ( 0 , length ) ) ) ; if ( result == 0 ) { result = groups . size ( ) > other . getGroups ( ) . size ( ) ? 1 : groups . size ( ) < other . getGroups ( ) . size ( ) ? - 1 : 0 ; } if ( result == 0 ) { result = extension . compareTo ( other . getExtension ( ) ) ; } if ( result == 0 ) { result = comparator . compare ( toVersionString ( ) , other . toVersionString ( ) ) ; } } return result ; }
|
Compares this version number with the specified version number for order . Returns a negative integer zero or a positive integer as this version number is less than equal to or greater than the specified version number .
|
3,343
|
protected static void logParsingIssue ( final String prefix , final SAXParseException e ) { final StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( prefix ) ; buffer . append ( " while reading UAS data: " ) ; buffer . append ( e . getMessage ( ) ) ; buffer . append ( " (line: " ) ; buffer . append ( e . getLineNumber ( ) ) ; if ( e . getSystemId ( ) != null ) { buffer . append ( " uri: " ) ; buffer . append ( e . getSystemId ( ) ) ; } buffer . append ( ")" ) ; LOG . warn ( buffer . toString ( ) ) ; }
|
Logs an issue while parsing XML .
|
3,344
|
private void transferToSpecificBuilderAndReset ( ) { if ( currentTag == Tag . VERSION ) { dataBuilder . setVersion ( buffer . toString ( ) ) ; } addToRobotBuilder ( ) ; addToBrowserBuilder ( ) ; addToOperatingSystemBuilder ( ) ; addToBrowserPatternBuilder ( ) ; addToBrowserTypeBuilder ( ) ; addToBrowserOsMappingBuilder ( ) ; addToOperatingSystemPatternBuilder ( ) ; addToDeviceBuilder ( ) ; addToDevicePatternBuilder ( ) ; buffer = new StringBuilder ( ) ; }
|
Transfers all characters of a specific tag to the corresponding builder and resets the string buffer .
|
3,345
|
private static void deleteCacheFile ( final File cacheFile ) { try { if ( cacheFile . delete ( ) ) { LOG . warn ( String . format ( MSG_CACHE_FILE_IS_DAMAGED_AND_DELETED , cacheFile . getPath ( ) ) ) ; } else { LOG . warn ( String . format ( MSG_CACHE_FILE_IS_DAMAGED , cacheFile . getPath ( ) ) ) ; } } catch ( final Exception e ) { LOG . warn ( String . format ( MSG_CACHE_FILE_IS_DAMAGED , cacheFile . getPath ( ) ) ) ; } }
|
Removes the given cache file because it contains damaged content .
|
3,346
|
private static DataStore readCacheFileAsFallback ( final DataReader reader , final File cacheFile , final Charset charset , final DataStore fallback ) { DataStore fallbackDataStore ; if ( ! isEmpty ( cacheFile , charset ) ) { final URL cacheFileUrl = UrlUtil . toUrl ( cacheFile ) ; try { fallbackDataStore = new CacheFileDataStore ( reader . read ( cacheFileUrl , charset ) , reader , cacheFileUrl , charset ) ; LOG . debug ( MSG_CACHE_FILE_IS_FILLED ) ; } catch ( final RuntimeException e ) { fallbackDataStore = fallback ; deleteCacheFile ( cacheFile ) ; } } else { fallbackDataStore = fallback ; LOG . debug ( MSG_CACHE_FILE_IS_EMPTY ) ; } return fallbackDataStore ; }
|
Tries to read the content of specified cache file and returns them as fallback data store . If the cache file contains unexpected data the given fallback data store will be returned instead .
|
3,347
|
public void activate ( InetAddress host , int port , Collection < String > nonProxyHosts ) { for ( String scheme : new String [ ] { "http" , "https" } ) { String currentProxyHost = System . getProperty ( scheme + ".proxyHost" ) ; String currentProxyPort = System . getProperty ( scheme + ".proxyPort" ) ; if ( currentProxyHost != null ) { originalProxies . put ( scheme , new InetSocketAddress ( currentProxyHost , Integer . parseInt ( currentProxyPort ) ) ) ; } System . setProperty ( scheme + ".proxyHost" , new InetSocketAddress ( host , port ) . getHostString ( ) ) ; System . setProperty ( scheme + ".proxyPort" , Integer . toString ( port ) ) ; } String currentNonProxyHosts = System . getProperty ( "http.nonProxyHosts" ) ; if ( currentNonProxyHosts == null ) { originalNonProxyHosts . clear ( ) ; } else { for ( String nonProxyHost : Splitter . on ( '|' ) . split ( currentNonProxyHosts ) ) { originalNonProxyHosts . add ( nonProxyHost ) ; } } System . setProperty ( "http.nonProxyHosts" , Joiner . on ( '|' ) . join ( nonProxyHosts ) ) ; }
|
Activates a proxy override for the given URI scheme .
|
3,348
|
public void deactivateAll ( ) { for ( String scheme : new String [ ] { "http" , "https" } ) { InetSocketAddress originalProxy = originalProxies . remove ( scheme ) ; if ( originalProxy != null ) { System . setProperty ( scheme + ".proxyHost" , originalProxy . getHostName ( ) ) ; System . setProperty ( scheme + ".proxyPort" , Integer . toString ( originalProxy . getPort ( ) ) ) ; } else { System . clearProperty ( scheme + ".proxyHost" ) ; System . clearProperty ( scheme + ".proxyPort" ) ; } } if ( originalNonProxyHosts . isEmpty ( ) ) { System . clearProperty ( "http.nonProxyHosts" ) ; } else { System . setProperty ( "http.nonProxyHosts" , Joiner . on ( '|' ) . join ( originalNonProxyHosts ) ) ; } originalNonProxyHosts . clear ( ) ; }
|
Deactivates all proxy overrides restoring the pre - existing proxy settings if any .
|
3,349
|
public ProxySelector getOriginalProxySelector ( ) { return new ProxySelector ( ) { public List < Proxy > select ( URI uri ) { InetSocketAddress address = originalProxies . get ( uri . getScheme ( ) ) ; if ( address != null && ! ( originalNonProxyHosts . contains ( uri . getHost ( ) ) ) ) { return Collections . singletonList ( new Proxy ( HTTP , address ) ) ; } else { return Collections . singletonList ( Proxy . NO_PROXY ) ; } } public void connectFailed ( URI uri , SocketAddress sa , IOException ioe ) { } } ; }
|
Used by the Betamax proxy so that it can use pre - existing proxy settings when forwarding requests that do not match anything on tape .
|
3,350
|
public void lookupChainedProxies ( HttpRequest request , Queue < ChainedProxy > chainedProxies ) { final InetSocketAddress originalProxy = originalProxies . get ( URI . create ( request . getUri ( ) ) . getScheme ( ) ) ; if ( originalProxy != null ) { ChainedProxy chainProxy = new ChainedProxyAdapter ( ) { public InetSocketAddress getChainedProxyAddress ( ) { return originalProxy ; } } ; chainedProxies . add ( chainProxy ) ; } else { chainedProxies . add ( ChainedProxyAdapter . FALLBACK_TO_DIRECT_CONNECTION ) ; } }
|
Used by LittleProxy to connect to a downstream proxy if there is one .
|
3,351
|
public void start ( String tapeName , Optional < TapeMode > mode , Optional < MatchRule > matchRule ) { if ( tape != null ) { throw new IllegalStateException ( "start called when Recorder is already started" ) ; } tape = getTapeLoader ( ) . loadTape ( tapeName ) ; tape . setMode ( mode . or ( configuration . getDefaultMode ( ) ) ) ; tape . setMatchRule ( matchRule . or ( configuration . getDefaultMatchRule ( ) ) ) ; for ( RecorderListener listener : listeners ) { listener . onRecorderStart ( tape ) ; } }
|
Starts the Recorder inserting a tape with the specified parameters .
|
3,352
|
public void stop ( ) { if ( tape == null ) { throw new IllegalStateException ( "stop called when Recorder is not started" ) ; } for ( RecorderListener listener : listeners ) { listener . onRecorderStop ( ) ; } getTapeLoader ( ) . writeTape ( tape ) ; tape = null ; }
|
Stops the Recorder and writes its current tape out to a file .
|
3,353
|
public Collection < String > getIgnoreHosts ( ) { if ( isIgnoreLocalhost ( ) ) { return new ImmutableSet . Builder < String > ( ) . addAll ( ignoreHosts ) . addAll ( Network . getLocalAddresses ( ) ) . build ( ) ; } else { return ignoreHosts ; } }
|
Hosts that are ignored by Betamax . Any connections made will be allowed to proceed normally and not be intercepted .
|
3,354
|
public static Map < String , Object > getAnnotationAttributes ( Annotation annotation , boolean classValuesAsString ) { Map < String , Object > attrs = new HashMap < > ( ) ; Method [ ] methods = annotation . annotationType ( ) . getDeclaredMethods ( ) ; for ( Method method : methods ) { if ( method . getParameterTypes ( ) . length == 0 && method . getReturnType ( ) != void . class ) { try { Object value = method . invoke ( annotation ) ; if ( classValuesAsString ) { if ( value instanceof Class ) { value = ( ( Class ) value ) . getName ( ) ; } else if ( value instanceof Class [ ] ) { Class [ ] clazzArray = ( Class [ ] ) value ; String [ ] newValue = new String [ clazzArray . length ] ; for ( int i = 0 ; i < clazzArray . length ; i ++ ) { newValue [ i ] = clazzArray [ i ] . getName ( ) ; } value = newValue ; } } attrs . put ( method . getName ( ) , value ) ; } catch ( Exception ex ) { throw new IllegalStateException ( "Could not obtain annotation attribute values" , ex ) ; } } } return attrs ; }
|
Retrieve the given annotation s attributes as a Map .
|
3,355
|
protected static void enableOrDisableExternalEntityParsing ( DocumentBuilderFactory factory , boolean enableExternalEntities ) { String [ ] externalGeneralEntitiesFeatures = { "http://xml.org/sax/features/external-general-entities" , "http://xerces.apache.org/xerces-j/features.html#external-general-entities" , "http://xerces.apache.org/xerces2-j/features.html#external-general-entities" , } ; boolean success = false ; for ( String feature : externalGeneralEntitiesFeatures ) { try { factory . setFeature ( feature , enableExternalEntities ) ; success = true ; break ; } catch ( ParserConfigurationException e ) { } } if ( ! success && failIfExternalEntityParsingCannotBeConfigured ) { throw new XMLBuilderRuntimeException ( new ParserConfigurationException ( "Failed to set 'external-general-entities' feature to " + enableExternalEntities ) ) ; } String [ ] externalParameterEntitiesFeatures = { "http://xml.org/sax/features/external-parameter-entities" , "http://xerces.apache.org/xerces-j/features.html#external-parameter-entities" , "http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities" , } ; success = false ; for ( String feature : externalParameterEntitiesFeatures ) { try { factory . setFeature ( feature , enableExternalEntities ) ; success = true ; break ; } catch ( ParserConfigurationException e ) { } } if ( ! success && failIfExternalEntityParsingCannotBeConfigured ) { throw new XMLBuilderRuntimeException ( new ParserConfigurationException ( "Failed to set 'external-parameter-entities' feature to " + enableExternalEntities ) ) ; } }
|
Explicitly enable or disable the external - general - entities and external - parameter - entities features of the underlying DocumentBuilderFactory .
|
3,356
|
protected static Document createDocumentImpl ( String name , String namespaceURI , boolean enableExternalEntities , boolean isNamespaceAware ) throws ParserConfigurationException , FactoryConfigurationError { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( isNamespaceAware ) ; enableOrDisableExternalEntityParsing ( factory , enableExternalEntities ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . newDocument ( ) ; Element rootElement = null ; if ( namespaceURI != null && namespaceURI . length ( ) > 0 ) { rootElement = document . createElementNS ( namespaceURI , name ) ; } else { rootElement = document . createElement ( name ) ; } document . appendChild ( rootElement ) ; return document ; }
|
Construct an XML Document with a default namespace with the given root element .
|
3,357
|
protected static Document parseDocumentImpl ( InputSource inputSource , boolean enableExternalEntities , boolean isNamespaceAware ) throws ParserConfigurationException , SAXException , IOException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( isNamespaceAware ) ; enableOrDisableExternalEntityParsing ( factory , enableExternalEntities ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . parse ( inputSource ) ; return document ; }
|
Return an XML Document parsed from the given input source .
|
3,358
|
protected void stripWhitespaceOnlyTextNodesImpl ( ) throws XPathExpressionException { XPathFactory xpathFactory = XPathFactory . newInstance ( ) ; XPathExpression xpathExp = xpathFactory . newXPath ( ) . compile ( "//text()[normalize-space(.) = '']" ) ; NodeList emptyTextNodes = ( NodeList ) xpathExp . evaluate ( this . getDocument ( ) , XPathConstants . NODESET ) ; for ( int i = 0 ; i < emptyTextNodes . getLength ( ) ; i ++ ) { Node emptyTextNode = emptyTextNodes . item ( i ) ; emptyTextNode . getParentNode ( ) . removeChild ( emptyTextNode ) ; } }
|
Find and delete from the underlying Document any text nodes that contain nothing but whitespace such as newlines and tab or space characters used to indent or pretty - print an XML document .
|
3,359
|
protected void importXMLBuilderImpl ( BaseXMLBuilder builder ) { assertElementContainsNoOrWhitespaceOnlyTextNodes ( this . xmlNode ) ; Node importedNode = getDocument ( ) . importNode ( builder . getDocument ( ) . getDocumentElement ( ) , true ) ; this . xmlNode . appendChild ( importedNode ) ; }
|
Imports another BaseXMLBuilder document into this document at the current position . The entire document provided is imported .
|
3,360
|
public Object xpathQuery ( String xpath , QName type , NamespaceContext nsContext ) throws XPathExpressionException { XPathFactory xpathFactory = XPathFactory . newInstance ( ) ; XPath xPath = xpathFactory . newXPath ( ) ; if ( nsContext != null ) { xPath . setNamespaceContext ( nsContext ) ; } XPathExpression xpathExp = xPath . compile ( xpath ) ; try { return xpathExp . evaluate ( this . xmlNode , type ) ; } catch ( IllegalArgumentException e ) { return null ; } }
|
Return the result of evaluating an XPath query on the builder s DOM using the given namespace . Returns null if the query finds nothing or finds a node that does not match the type specified by returnType .
|
3,361
|
public Object xpathQuery ( String xpath , QName type ) throws XPathExpressionException { return xpathQuery ( xpath , type , null ) ; }
|
Return the result of evaluating an XPath query on the builder s DOM . Returns null if the query finds nothing or finds a node that does not match the type specified by returnType .
|
3,362
|
protected Element elementImpl ( String name , String namespaceURI ) { assertElementContainsNoOrWhitespaceOnlyTextNodes ( this . xmlNode ) ; if ( namespaceURI == null ) { return getDocument ( ) . createElement ( name ) ; } else { return getDocument ( ) . createElementNS ( namespaceURI , name ) ; } }
|
Add a named and namespaced XML element to the document as a child of this builder s node .
|
3,363
|
protected Element elementBeforeImpl ( String name ) { String prefix = getPrefixFromQualifiedName ( name ) ; String namespaceURI = this . xmlNode . lookupNamespaceURI ( prefix ) ; return elementBeforeImpl ( name , namespaceURI ) ; }
|
Add a named XML element to the document as a sibling element that precedes the position of this builder node .
|
3,364
|
protected Element elementBeforeImpl ( String name , String namespaceURI ) { Node parentNode = this . xmlNode . getParentNode ( ) ; assertElementContainsNoOrWhitespaceOnlyTextNodes ( parentNode ) ; Element newElement = ( namespaceURI == null ? getDocument ( ) . createElement ( name ) : getDocument ( ) . createElementNS ( namespaceURI , name ) ) ; parentNode . insertBefore ( newElement , this . xmlNode ) ; return newElement ; }
|
Add a named and namespaced XML element to the document as a sibling element that precedes the position of this builder node .
|
3,365
|
protected void attributeImpl ( String name , String value ) { if ( ! ( this . xmlNode instanceof Element ) ) { throw new RuntimeException ( "Cannot add an attribute to non-Element underlying node: " + this . xmlNode ) ; } ( ( Element ) xmlNode ) . setAttribute ( name , value ) ; }
|
Add a named attribute value to the element for this builder node .
|
3,366
|
protected void textImpl ( String value , boolean replaceText ) { if ( value == null ) { throw new IllegalArgumentException ( "Illegal null text value" ) ; } if ( replaceText ) { xmlNode . setTextContent ( value ) ; } else { xmlNode . appendChild ( getDocument ( ) . createTextNode ( value ) ) ; } }
|
Add or replace the text value of an element for this builder node .
|
3,367
|
protected void instructionImpl ( String target , String data ) { xmlNode . appendChild ( getDocument ( ) . createProcessingInstruction ( target , data ) ) ; }
|
Add an instruction to the element represented by this builder node .
|
3,368
|
protected void insertInstructionImpl ( String target , String data ) { getDocument ( ) . insertBefore ( getDocument ( ) . createProcessingInstruction ( target , data ) , xmlNode ) ; }
|
Insert an instruction before the element represented by this builder node .
|
3,369
|
protected void namespaceImpl ( String prefix , String namespaceURI ) { if ( ! ( this . xmlNode instanceof Element ) ) { throw new RuntimeException ( "Cannot add an attribute to non-Element underlying node: " + this . xmlNode ) ; } if ( prefix != null && prefix . length ( ) > 0 ) { ( ( Element ) xmlNode ) . setAttributeNS ( "http://www.w3.org/2000/xmlns/" , "xmlns:" + prefix , namespaceURI ) ; } else { ( ( Element ) xmlNode ) . setAttributeNS ( "http://www.w3.org/2000/xmlns/" , "xmlns" , namespaceURI ) ; } }
|
Add an XML namespace attribute to this builder s element node .
|
3,370
|
public String asString ( ) throws TransformerException { Properties outputProperties = new Properties ( ) ; outputProperties . put ( javax . xml . transform . OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; return asString ( outputProperties ) ; }
|
Serialize the XML document to a string excluding the XML declaration .
|
3,371
|
public static XMLBuilder2 parse ( InputSource inputSource , boolean enableExternalEntities , boolean isNamespaceAware ) { try { return new XMLBuilder2 ( parseDocumentImpl ( inputSource , enableExternalEntities , isNamespaceAware ) ) ; } catch ( ParserConfigurationException e ) { throw wrapExceptionAsRuntimeException ( e ) ; } catch ( SAXException e ) { throw wrapExceptionAsRuntimeException ( e ) ; } catch ( IOException e ) { throw wrapExceptionAsRuntimeException ( e ) ; } }
|
Construct a builder from an existing XML document . The provided XML document will be parsed and an XMLBuilder2 object referencing the document s root element will be returned .
|
3,372
|
public static XMLBuilder2 parse ( String xmlString , boolean enableExternalEntities , boolean isNamespaceAware ) { return XMLBuilder2 . parse ( new InputSource ( new StringReader ( xmlString ) ) , enableExternalEntities , isNamespaceAware ) ; }
|
Construct a builder from an existing XML document string . The provided XML document will be parsed and an XMLBuilder2 object referencing the document s root element will be returned .
|
3,373
|
public static XMLBuilder2 parse ( File xmlFile , boolean enableExternalEntities , boolean isNamespaceAware ) { try { return XMLBuilder2 . parse ( new InputSource ( new FileReader ( xmlFile ) ) , enableExternalEntities , isNamespaceAware ) ; } catch ( FileNotFoundException e ) { throw wrapExceptionAsRuntimeException ( e ) ; } }
|
Construct a builder from an existing XML document file . The provided XML document will be parsed and an XMLBuilder2 object referencing the document s root element will be returned .
|
3,374
|
private void initProperties ( ) { center = new SimpleObjectProperty < > ( ) ; center . addListener ( ( observable , oldValue , newValue ) -> { if ( newValue != lastCoordinateFromMap . get ( ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "center changed from {} to {}" , oldValue , newValue ) ; } setCenterInMap ( ) ; } } ) ; zoom = new SimpleDoubleProperty ( INITIAL_ZOOM ) ; zoom . addListener ( ( observable , oldValue , newValue ) -> { final Long rounded = Math . round ( ( Double ) newValue ) ; if ( ! Objects . equals ( rounded , lastZoomFromMap . get ( ) ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "zoom changed from {} to {}" , oldValue , rounded ) ; } setZoomInMap ( ) ; } } ) ; animationDuration = new SimpleIntegerProperty ( 0 ) ; mapType = new SimpleObjectProperty < > ( MapType . OSM ) ; mapType . addListener ( ( observable , oldValue , newValue ) -> { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "map type changed from {} to {}" , oldValue , newValue ) ; } if ( ! checkApiKey ( newValue ) ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "no api key defined for map type {}" , newValue ) ; } mapType . set ( oldValue ) ; } if ( MapType . WMS == newValue ) { boolean wmsValid = false ; if ( wmsParam . isPresent ( ) ) { String url = wmsParam . get ( ) . getUrl ( ) ; if ( null != url && ! url . isEmpty ( ) ) { wmsValid = true ; } } if ( ! wmsValid ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "no wms params defined for map type {}" , newValue ) ; } mapType . set ( oldValue ) ; } } if ( MapType . XYZ . equals ( newValue ) ) { boolean xyzValid = false ; if ( xyzParam . isPresent ( ) ) { String url = xyzParam . get ( ) . getUrl ( ) ; if ( null != url && ! url . isEmpty ( ) ) { xyzValid = true ; } } if ( ! xyzValid ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "no xyz params defined for map type {}" , newValue ) ; } mapType . set ( oldValue ) ; } } setMapTypeInMap ( ) ; } ) ; }
|
initializes the JavaFX properties .
|
3,375
|
private void setCenterInMap ( ) { final Coordinate actCenter = getCenter ( ) ; if ( getInitialized ( ) && null != actCenter ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "setting center in OpenLayers map: {}, animation: {}" , actCenter , animationDuration . get ( ) ) ; } jsMapView . call ( "setCenter" , actCenter . getLatitude ( ) , actCenter . getLongitude ( ) , animationDuration . get ( ) ) ; } }
|
sets the value of the center property in the OL map .
|
3,376
|
private void setZoomInMap ( ) { if ( getInitialized ( ) ) { final int zoomInt = ( int ) getZoom ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "setting zoom in OpenLayers map: {}, animation: {}" , zoomInt , animationDuration . get ( ) ) ; } jsMapView . call ( "setZoom" , zoomInt , animationDuration . get ( ) ) ; } }
|
sets the value of the actual zoom property in the OL map .
|
3,377
|
private boolean checkApiKey ( final MapType mapTypeToCheck ) { switch ( requireNonNull ( mapTypeToCheck ) ) { case BINGMAPS_ROAD : case BINGMAPS_AERIAL : return bingMapsApiKey . isPresent ( ) ; default : return true ; } }
|
checks if the given map type needs an api key and if so if it is set .
|
3,378
|
private void setMapTypeInMap ( ) { if ( getInitialized ( ) ) { final String mapTypeName = getMapType ( ) . toString ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "setting map type in OpenLayers map: {}" , mapTypeName ) ; } bingMapsApiKey . ifPresent ( apiKey -> jsMapView . call ( "setBingMapsApiKey" , apiKey ) ) ; wmsParam . ifPresent ( wmsParam -> { jsMapView . call ( "newWMSParams" ) ; jsMapView . call ( "setWMSParamsUrl" , wmsParam . getUrl ( ) ) ; wmsParam . getParams ( ) . forEach ( ( key , value ) -> jsMapView . call ( "addWMSParamsParams" , key , value ) ) ; } ) ; xyzParam . ifPresent ( xyzParam -> { jsMapView . call ( "setXYZParams" , xyzParam . toJSON ( ) ) ; } ) ; jsMapView . call ( "setMapType" , mapTypeName ) ; } }
|
sets the value of the mapType property in the OL map .
|
3,379
|
public MapView addCoordinateLine ( final CoordinateLine coordinateLine ) { if ( ! getInitialized ( ) ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( MAP_VIEW_NOT_YET_INITIALIZED ) ; } } else { synchronized ( coordinateLines ) { final String id = requireNonNull ( coordinateLine ) . getId ( ) ; if ( ! coordinateLines . containsKey ( id ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "adding coordinate line {}" , coordinateLine ) ; } final JSObject jsCoordinateLine = ( JSObject ) jsMapView . call ( "getCoordinateLine" , id ) ; coordinateLine . getCoordinateStream ( ) . forEach ( ( coord ) -> jsCoordinateLine . call ( "addCoordinate" , coord . getLatitude ( ) , coord . getLongitude ( ) ) ) ; final javafx . scene . paint . Color color = coordinateLine . getColor ( ) ; jsCoordinateLine . call ( "setColor" , color . getRed ( ) * 255 , color . getGreen ( ) * 255 , color . getBlue ( ) * 255 , color . getOpacity ( ) ) ; final javafx . scene . paint . Color fillColor = coordinateLine . getFillColor ( ) ; jsCoordinateLine . call ( "setFillColor" , fillColor . getRed ( ) * 255 , fillColor . getGreen ( ) * 255 , fillColor . getBlue ( ) * 255 , fillColor . getOpacity ( ) ) ; jsCoordinateLine . call ( "setWidth" , coordinateLine . getWidth ( ) ) ; jsCoordinateLine . call ( "setClosed" , coordinateLine . isClosed ( ) ) ; jsCoordinateLine . call ( "seal" ) ; final ChangeListener < Boolean > changeListener = ( observable , newValue , oldValue ) -> setCoordinateLineVisibleInMap ( id ) ; coordinateLine . visibleProperty ( ) . addListener ( changeListener ) ; coordinateLineListeners . put ( id , new CoordinateLineListener ( changeListener ) ) ; coordinateLines . put ( id , new WeakReference < > ( coordinateLine , weakReferenceQueue ) ) ; setCoordinateLineVisibleInMap ( id ) ; } } } return this ; }
|
add a CoordinateLine to the map . If it was already added nothing happens . The MapView only stores a weak reference to the object so the caller must keep a reference in order to prevent the line to be removed from the map . This method must only be called after the map is initialized otherwise a warning is logged and the coordinateLine is not added to the map .
|
3,380
|
private void setCoordinateLineVisibleInMap ( final String coordinateLineId ) { if ( null != coordinateLineId ) { final WeakReference < CoordinateLine > coordinateLineWeakReference = coordinateLines . get ( coordinateLineId ) ; if ( null != coordinateLineWeakReference ) { final CoordinateLine coordinateLine = coordinateLineWeakReference . get ( ) ; if ( null != coordinateLine ) { if ( coordinateLine . getVisible ( ) ) { jsMapView . call ( "showCoordinateLine" , coordinateLineId ) ; } else { jsMapView . call ( "hideCoordinateLine" , coordinateLineId ) ; } } } } }
|
shows or hides the coordinateline in the map according to it s visible property .
|
3,381
|
public MapView addLabel ( final MapLabel mapLabel ) { if ( ! getInitialized ( ) ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( MAP_VIEW_NOT_YET_INITIALIZED ) ; } } else { if ( null == requireNonNull ( mapLabel ) . getPosition ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "label with no position was not added: {}" , mapLabel ) ; } return this ; } final String id = mapLabel . getId ( ) ; synchronized ( mapCoordinateElements ) { if ( mapLabel . getMarker ( ) . isPresent ( ) && ! mapCoordinateElements . containsKey ( mapLabel . getMarker ( ) . get ( ) . getId ( ) ) ) { return this ; } if ( ! mapCoordinateElements . containsKey ( id ) ) { addMapCoordinateElement ( mapLabel ) ; jsMapView . call ( "addLabel" , id , mapLabel . getText ( ) , mapLabel . getCssClass ( ) , mapLabel . getPosition ( ) . getLatitude ( ) , mapLabel . getPosition ( ) . getLongitude ( ) , mapLabel . getOffsetX ( ) , mapLabel . getOffsetY ( ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "add label in OpenLayers map {}" , mapLabel ) ; } setMarkerVisibleInMap ( id ) ; } } } return this ; }
|
adds a label to the map . If it was already added nothing is changed . If the MapView is not yet initialized a warning is logged and nothing changes . If the label has no coordinate set it is not added and a logging entry is written .
|
3,382
|
private void addMapCoordinateElement ( final MapCoordinateElement mapCoordinateElement ) { final String id = mapCoordinateElement . getId ( ) ; final ChangeListener < Coordinate > coordinateChangeListener = ( observable , oldValue , newValue ) -> moveMapCoordinateElementInMap ( id ) ; final ChangeListener < Boolean > visibileChangeListener = ( observable , oldValue , newValue ) -> setMarkerVisibleInMap ( id ) ; final ChangeListener < String > cssChangeListener = ( observable , oldValue , newValue ) -> setMapCoordinateElementCss ( id , newValue ) ; mapCoordinateElementListeners . put ( id , new MapCoordinateElementListener ( coordinateChangeListener , visibileChangeListener , cssChangeListener ) ) ; mapCoordinateElement . positionProperty ( ) . addListener ( coordinateChangeListener ) ; mapCoordinateElement . visibleProperty ( ) . addListener ( visibileChangeListener ) ; mapCoordinateElement . cssClassProperty ( ) . addListener ( cssChangeListener ) ; mapCoordinateElements . put ( id , new WeakReference < > ( mapCoordinateElement , weakReferenceQueue ) ) ; }
|
sets up the internal information about a MapCoordinate Element .
|
3,383
|
private void setMarkerVisibleInMap ( final String id ) { if ( null != id ) { final WeakReference < MapCoordinateElement > weakReference = mapCoordinateElements . get ( id ) ; if ( null != weakReference ) { final MapCoordinateElement mapCoordinateElement = weakReference . get ( ) ; if ( null != mapCoordinateElement ) { if ( mapCoordinateElement . getVisible ( ) ) { jsMapView . call ( "showMapObject" , mapCoordinateElement . getId ( ) ) ; } else { jsMapView . call ( "hideMapObject" , mapCoordinateElement . getId ( ) ) ; } } } } }
|
sets the visibility of a MapCoordinateElement in the map .
|
3,384
|
private void moveMapCoordinateElementInMap ( final String id ) { if ( getInitialized ( ) && null != id ) { final WeakReference < MapCoordinateElement > weakReference = mapCoordinateElements . get ( id ) ; if ( null != weakReference ) { final MapCoordinateElement mapCoordinateElement = weakReference . get ( ) ; if ( null != mapCoordinateElement ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "move element in OpenLayers map to {}" , mapCoordinateElement ) ; } jsMapView . call ( "moveMapObject" , mapCoordinateElement . getId ( ) , mapCoordinateElement . getPosition ( ) . getLatitude ( ) , mapCoordinateElement . getPosition ( ) . getLongitude ( ) ) ; } } } }
|
adjusts the mapCoordinateElement s position in the map .
|
3,385
|
public MapView addMarker ( final Marker marker ) { if ( ! getInitialized ( ) ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( MAP_VIEW_NOT_YET_INITIALIZED ) ; } } else { if ( null == requireNonNull ( marker ) . getPosition ( ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "marker with no position was not added: {}" , marker ) ; } return this ; } final String id = marker . getId ( ) ; synchronized ( mapCoordinateElements ) { if ( ! mapCoordinateElements . containsKey ( id ) ) { addMapCoordinateElement ( marker ) ; jsMapView . call ( "addMarker" , id , marker . getImageURL ( ) . toExternalForm ( ) , marker . getPosition ( ) . getLatitude ( ) , marker . getPosition ( ) . getLongitude ( ) , marker . getOffsetX ( ) , marker . getOffsetY ( ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "add marker in OpenLayers map {}" , marker ) ; } setMarkerVisibleInMap ( id ) ; } } marker . getMapLabel ( ) . ifPresent ( this :: addLabel ) ; } return this ; }
|
adds a marker to the map . If it was already added nothing is changed . If the MapView is not yet initialized a warning is logged and nothing changes . If the marker has no coordinate set it is not added and a logging entry is written .
|
3,386
|
@ SuppressWarnings ( "UnusedDeclaration" ) private String createDataURI ( final URL imageURL ) { return imgCache . computeIfAbsent ( imageURL , url -> { String dataUrl = null ; try ( final InputStream isGuess = url . openStream ( ) ; final InputStream isConvert = url . openStream ( ) ; final ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ) { final String contentType = URLConnection . guessContentTypeFromStream ( isGuess ) ; if ( null != contentType ) { final byte [ ] chunk = new byte [ 4096 ] ; int bytesRead ; while ( ( bytesRead = isConvert . read ( chunk ) ) > 0 ) { os . write ( chunk , 0 , bytesRead ) ; } os . flush ( ) ; dataUrl = "data:" + contentType + ";base64," + Base64 . getEncoder ( ) . encodeToString ( os . toByteArray ( ) ) ; } else { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "could not get content type from {}" , imageURL . toExternalForm ( ) ) ; } } } catch ( final IOException e ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "error loading image" , e ) ; } } if ( null == dataUrl ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "could not create data url from {}" , imageURL . toExternalForm ( ) ) ; } } return dataUrl ; } ) ; }
|
loads an image and converts it s data to a base64 encoded data url .
|
3,387
|
public void showLink ( final String href ) { if ( null != href && ! href . isEmpty ( ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "JS asks to browse to {}" , href ) ; } if ( ! Desktop . isDesktopSupported ( ) ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "no desktop support for displaying {}" , href ) ; } } else { try { Desktop . getDesktop ( ) . browse ( new URI ( href ) ) ; } catch ( final IOException | URISyntaxException e ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "can't display {}" , href , e ) ; } } } } }
|
called when an a href in the map is clicked and shows the URL in the default browser .
|
3,388
|
private void processMarkerClicked ( final String name , final ClickType clickType ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "JS reports marker {} clicked {}" , name , clickType ) ; } synchronized ( mapCoordinateElements ) { if ( mapCoordinateElements . containsKey ( name ) ) { final MapCoordinateElement mapCoordinateElement = mapCoordinateElements . get ( name ) . get ( ) ; EventType < MarkerEvent > eventType = null ; switch ( clickType ) { case LEFT : eventType = MarkerEvent . MARKER_CLICKED ; break ; case DOUBLE : eventType = MarkerEvent . MARKER_DOUBLECLICKED ; break ; case RIGHT : eventType = MarkerEvent . MARKER_RIGHTCLICKED ; break ; case MOUSEDOWN : eventType = MarkerEvent . MARKER_MOUSEDOWN ; break ; case MOUSEUP : eventType = MarkerEvent . MARKER_MOUSEUP ; break ; case ENTERED : eventType = MarkerEvent . MARKER_ENTERED ; break ; case EXITED : eventType = MarkerEvent . MARKER_EXITED ; break ; } fireEvent ( new MarkerEvent ( eventType , ( Marker ) mapCoordinateElement ) ) ; } } }
|
processes a marker click
|
3,389
|
private void processLabelClicked ( final String name , final ClickType clickType ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "JS reports label {} clicked {}" , name , clickType ) ; } synchronized ( mapCoordinateElements ) { if ( mapCoordinateElements . containsKey ( name ) ) { final MapCoordinateElement mapCoordinateElement = mapCoordinateElements . get ( name ) . get ( ) ; if ( mapCoordinateElement instanceof MapLabel ) { EventType < MapLabelEvent > eventType = null ; switch ( clickType ) { case LEFT : eventType = MapLabelEvent . MAPLABEL_CLICKED ; break ; case DOUBLE : eventType = MapLabelEvent . MAPLABEL_DOUBLECLICKED ; break ; case RIGHT : eventType = MapLabelEvent . MAPLABEL_RIGHTCLICKED ; break ; case MOUSEDOWN : eventType = MapLabelEvent . MAPLABEL_MOUSEDOWN ; break ; case MOUSEUP : eventType = MapLabelEvent . MAPLABEL_MOUSEUP ; break ; case ENTERED : eventType = MapLabelEvent . MAPLABEL_ENTERED ; break ; case EXITED : eventType = MapLabelEvent . MAPLABEL_EXITED ; break ; } fireEvent ( new MapLabelEvent ( eventType , ( MapLabel ) mapCoordinateElement ) ) ; } } } }
|
called when a label was clicked .
|
3,390
|
public void zoomChanged ( double newZoom ) { final long roundedZoom = Math . round ( newZoom ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "JS reports zoom value {}" , roundedZoom ) ; } lastZoomFromMap . set ( roundedZoom ) ; setZoom ( roundedZoom ) ; }
|
called when the user changed the zoom with the controls in the map .
|
3,391
|
public void extentSelected ( double latMin , double lonMin , double latMax , double lonMax ) { final Extent extent = Extent . forCoordinates ( new Coordinate ( latMin , lonMin ) , new Coordinate ( latMax , lonMax ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "JS reports extend selected: {}" , extent ) ; } fireEvent ( new MapViewEvent ( MapViewEvent . MAP_EXTENT , extent ) ) ; }
|
called when the user selected an extent by dragging the mouse with modifier pressed .
|
3,392
|
public void extentChanged ( double latMin , double lonMin , double latMax , double lonMax ) { final Extent extent = Extent . forCoordinates ( new Coordinate ( latMin , lonMin ) , new Coordinate ( latMax , lonMax ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "JS reports extend change: {}" , extent ) ; } fireEvent ( new MapViewEvent ( MapViewEvent . MAP_BOUNDING_EXTENT , extent ) ) ; }
|
called when the map extent changed by changing the center or zoom of the map .
|
3,393
|
public static Extent forCoordinates ( Collection < ? extends Coordinate > coordinates ) { requireNonNull ( coordinates ) ; if ( coordinates . size ( ) < 2 ) { throw new IllegalArgumentException ( ) ; } double minLatitude = Double . MAX_VALUE ; double maxLatitude = - Double . MAX_VALUE ; double minLongitude = Double . MAX_VALUE ; double maxLongitude = - Double . MAX_VALUE ; for ( Coordinate coordinate : coordinates ) { minLatitude = Math . min ( minLatitude , coordinate . getLatitude ( ) ) ; maxLatitude = Math . max ( maxLatitude , coordinate . getLatitude ( ) ) ; minLongitude = Math . min ( minLongitude , coordinate . getLongitude ( ) ) ; maxLongitude = Math . max ( maxLongitude , coordinate . getLongitude ( ) ) ; } return new Extent ( new Coordinate ( minLatitude , minLongitude ) , new Coordinate ( maxLatitude , maxLongitude ) ) ; }
|
creates the extent of the given coordinates .
|
3,394
|
private URLStreamHandler getURLStreamHandler ( final String protocol ) { try { final Method method = URL . class . getDeclaredMethod ( "getURLStreamHandler" , String . class ) ; method . setAccessible ( true ) ; return ( URLStreamHandler ) method . invoke ( null , protocol ) ; } catch ( final Exception e ) { if ( logger . isWarnEnabled ( ) ) { logger . warn ( "could not access URL.getUrlStreamHandler" ) ; } return null ; } }
|
returns the URL class s stream handler for a protocol . this uses inspection .
|
3,395
|
public URLStreamHandler createURLStreamHandler ( final String protocol ) { if ( null == protocol ) { throw new IllegalArgumentException ( "null protocol not allowed" ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "need to create URLStreamHandler for protocol {}" , protocol ) ; } final String proto = protocol . toLowerCase ( ) ; if ( PROTO_HTTP . equals ( proto ) || PROTO_HTTPS . equals ( proto ) ) { return new URLStreamHandler ( ) { protected URLConnection openConnection ( final URL url ) throws IOException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "should open connection to {}" , url . toExternalForm ( ) ) ; } final URLConnection defaultUrlConnection = new URL ( protocol , url . getHost ( ) , url . getPort ( ) , url . getFile ( ) , handlers . get ( protocol ) ) . openConnection ( ) ; if ( ! cache . urlShouldBeCached ( url ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "not using cache for {}" , url ) ; } return defaultUrlConnection ; } final Path cacheFile = cache . filenameForURL ( url ) ; if ( cache . isCached ( url ) ) { return new CachingHttpURLConnection ( cache , ( HttpURLConnection ) defaultUrlConnection ) ; } else { switch ( proto ) { case PROTO_HTTP : return new CachingHttpURLConnection ( cache , ( HttpURLConnection ) defaultUrlConnection ) ; case PROTO_HTTPS : return new CachingHttpsURLConnection ( cache , ( HttpsURLConnection ) defaultUrlConnection ) ; } } throw new IOException ( "no matching handler" ) ; } protected URLConnection openConnection ( final URL u , final Proxy p ) throws IOException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "should open connection to {} via {}" , u . toExternalForm ( ) , p ) ; } final URLConnection defaultUrlConnection = new URL ( protocol , u . getHost ( ) , u . getPort ( ) , u . getFile ( ) , handlers . get ( protocol ) ) . openConnection ( p ) ; return defaultUrlConnection ; } } ; } return null ; }
|
default Handler for http and https .
|
3,396
|
public static Marker createProvided ( Provided provided ) { requireNonNull ( provided ) ; return new Marker ( Marker . class . getResource ( "/markers/" + provided . getFilename ( ) ) , provided . getOffsetX ( ) , provided . getOffsetY ( ) ) ; }
|
return a provided Marker with the given color .
|
3,397
|
public Marker attachLabel ( MapLabel mapLabel ) { optMapLabel = Optional . of ( requireNonNull ( mapLabel ) ) ; mapLabel . setMarker ( this ) ; mapLabel . visibleProperty ( ) . bind ( visibleProperty ( ) ) ; mapLabel . positionProperty ( ) . bind ( positionProperty ( ) ) ; return this ; }
|
attaches the MapLabel to this Marker
|
3,398
|
public Marker detachLabel ( ) { optMapLabel . ifPresent ( mapLabel -> { mapLabel . setMarker ( null ) ; mapLabel . visibleProperty ( ) . unbind ( ) ; mapLabel . positionProperty ( ) . unbind ( ) ; } ) ; optMapLabel = Optional . empty ( ) ; return this ; }
|
detaches an attached Label .
|
3,399
|
public Object parse ( SerializerHandler serializerHandler , InputStream response , boolean debugMode ) throws XMLRPCException { try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document dom = builder . parse ( response ) ; if ( debugMode ) { printDocument ( dom , System . out ) ; } Element e = dom . getDocumentElement ( ) ; if ( ! e . getNodeName ( ) . equals ( XMLRPCClient . METHOD_RESPONSE ) ) { throw new XMLRPCException ( "MethodResponse root tag is missing." ) ; } e = XMLUtil . getOnlyChildElement ( e . getChildNodes ( ) ) ; if ( e . getNodeName ( ) . equals ( XMLRPCClient . PARAMS ) ) { e = XMLUtil . getOnlyChildElement ( e . getChildNodes ( ) ) ; if ( ! e . getNodeName ( ) . equals ( XMLRPCClient . PARAM ) ) { throw new XMLRPCException ( "The params tag must contain a param tag." ) ; } return getReturnValueFromElement ( serializerHandler , e ) ; } else if ( e . getNodeName ( ) . equals ( XMLRPCClient . FAULT ) ) { @ SuppressWarnings ( "unchecked" ) Map < String , Object > o = ( Map < String , Object > ) getReturnValueFromElement ( serializerHandler , e ) ; throw new XMLRPCServerException ( ( String ) o . get ( FAULT_STRING ) , ( Integer ) o . get ( FAULT_CODE ) ) ; } throw new XMLRPCException ( "The methodResponse tag must contain a fault or params tag." ) ; } catch ( XMLRPCServerException e ) { throw e ; } catch ( Exception ex ) { throw new XMLRPCException ( "Error getting result from server." , ex ) ; } }
|
The given InputStream must contain the xml response from an xmlrpc server . This method extract the content of it as an object .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.