idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
24,300 | public MethodInfo get ( String beanName , String methodName ) { return this . cache . get ( new Key ( beanName , methodName ) ) ; } | Get a method from the MethodCache . | 33 | 8 |
24,301 | public String getMessage ( Throwable exception ) { String message ; if ( getExceptionToMessage ( ) != null ) { message = getExceptionToMessage ( ) . get ( exception . getClass ( ) ) ; if ( StringUtils . hasText ( message ) ) { return message ; } // map entry with a null value if ( getExceptionToMessage ( ) . containsKey ( exception . getClass ( ) ) ) { return exception . getMessage ( ) ; } } if ( isSendExceptionMessage ( ) ) { return exception . getMessage ( ) ; } return getDefaultExceptionMessage ( ) ; } | Returns an error message for the supplied exception and based on this configuration . | 127 | 14 |
24,302 | @ Deprecated public Configuration copy ( ) { Configuration copy = new Configuration ( ) ; copy . apiUrl = apiUrl ; copy . domain = domain ; copy . apiKey = apiKey ; copy . mailRequestCallbackFactory = mailRequestCallbackFactory ; copy . mailSendFilter = mailSendFilter ; //noinspection Convert2Diamond copy . defaultParameters = new MultivaluedHashMap < String , String > ( defaultParameters ) ; //NOSONAR copy . converters . addAll ( converters ) ; return copy ; } | Creates a copy of this configuration . | 110 | 8 |
24,303 | public MailBuilder from ( String name , String email ) { return param ( "from" , email ( name , email ) ) ; } | Sets the address of the sender . | 28 | 8 |
24,304 | public MailBuilder to ( String name , String email ) { return param ( "to" , email ( name , email ) ) ; } | Adds a destination recipient s address . | 28 | 7 |
24,305 | public MailBuilder cc ( String name , String email ) { return param ( "cc" , email ( name , email ) ) ; } | Adds a CC recipient s address . | 28 | 7 |
24,306 | public MailBuilder bcc ( String name , String email ) { return param ( "bcc" , email ( name , email ) ) ; } | Adds a BCC recipient s address . | 30 | 7 |
24,307 | public void sendAsync ( ) { if ( ! configuration . mailSendFilter ( ) . filter ( this ) ) return ; MailRequestCallbackFactory factory = configuration . mailRequestCallbackFactory ( ) ; if ( factory == null ) { prepareSend ( ) ; request ( ) . async ( ) . post ( entity ( ) ) ; } else sendAsync ( factory . create ( this ) ) ; } | Sends the email asynchronously . It uses the configuration provided default callback if available ignoring the outcome otherwise . | 81 | 22 |
24,308 | public MultipartBuilder attachment ( InputStream is , String filename ) { return bodyPart ( new StreamDataBodyPart ( ATTACHMENT_NAME , is , filename ) ) ; } | Adds a named attachment . | 38 | 5 |
24,309 | public MultipartBuilder attachment ( String content , String filename ) { ByteArrayInputStream is = new ByteArrayInputStream ( content . getBytes ( ) ) ; return bodyPart ( new StreamDataBodyPart ( ATTACHMENT_NAME , is , filename ) ) ; } | Adds an attachment directly by content . | 57 | 7 |
24,310 | public MultipartBuilder inline ( InputStream is , String cidName ) { return bodyPart ( new StreamDataBodyPart ( "inline" , is , cidName ) ) ; } | Adds a named inline attachment . | 40 | 6 |
24,311 | public MailContent row ( String firstCell , String secondCell , String thirdCell ) { return tag ( "tr" ) . cell ( firstCell ) . cell ( secondCell ) . cell ( thirdCell ) . end ( ) ; } | Adds a new row with three columns . | 49 | 8 |
24,312 | public MailBuilder mail ( ) { if ( mailBuilder != null ) return mailBuilder . content ( build ( ) ) ; else return MailBuilder . using ( configuration ) . content ( build ( ) ) ; } | Convenience method for chaining the creation of the content body with the creation of the mail envelope . | 43 | 21 |
24,313 | public Builder end ( ) { if ( ends . isEmpty ( ) ) throw new IllegalStateException ( "No pending tag/section to close." ) ; String tag = ends . pop ( ) ; html . a ( tag ) ; if ( newLineAfterTheseTags . contains ( tag . toLowerCase ( ) ) ) { html . nl ( ) ; text . nl ( ) ; } return this ; } | Closes the last opened tag or section . | 87 | 9 |
24,314 | public < T > Builder row ( T firstCell , T secondCell ) { return tag ( "tr" ) . cell ( firstCell , false ) . cell ( secondCell ) . end ( ) ; } | Adds a new row with two columns . | 43 | 8 |
24,315 | public < T > Builder rowh ( String label , T data ) { return tag ( "tr" ) . cellHeader ( label , false ) . cell ( data ) . end ( ) ; } | Adds a new row with two columns the first one being a header cell . | 41 | 15 |
24,316 | public static Object flatten ( Object array ) { Preconditions . checkArgument ( array . getClass ( ) . isArray ( ) , "array" ) ; Class < ? > type = getType ( array ) ; int [ ] dimensions = getDimensions ( array ) ; int length = length ( dimensions ) ; Object flattened = Array . newInstance ( type , length ) ; flatten ( array , flattened , dimensions , 0 ) ; return flattened ; } | Flatten a multi - dimensional array into a one - dimensional array . | 96 | 14 |
24,317 | public static Object unflatten ( Object array , int [ ] dimensions ) { Class < ? > type = getType ( array ) ; return unflatten ( type , array , dimensions , 0 ) ; } | Un - flatten a one - dimensional array into an multi - dimensional array based on the provided dimensions . | 41 | 21 |
24,318 | public static byte [ ] sha1 ( byte [ ] input ) { MessageDigest messageDigest = sha1Digest . get ( ) ; if ( messageDigest == null ) { try { messageDigest = MessageDigest . getInstance ( "SHA1" ) ; sha1Digest . set ( messageDigest ) ; } catch ( NoSuchAlgorithmException e ) { throw new UaRuntimeException ( StatusCodes . Bad_InternalError , e ) ; } } return messageDigest . digest ( input ) ; } | Compute the SHA1 digest for a given input . | 116 | 11 |
24,319 | private static ByteBuf encode ( MessageType messageType , Consumer < ByteBuf > messageEncoder , ByteBuf buffer ) throws UaException { buffer . writeMedium ( MessageType . toMediumInt ( messageType ) ) ; buffer . writeByte ( ' ' ) ; int lengthIndex = buffer . writerIndex ( ) ; buffer . writeInt ( 0 ) ; int indexBefore = buffer . writerIndex ( ) ; messageEncoder . accept ( buffer ) ; int indexAfter = buffer . writerIndex ( ) ; int bytesWritten = indexAfter - indexBefore ; buffer . writerIndex ( lengthIndex ) ; buffer . writeInt ( 8 + bytesWritten ) ; buffer . writerIndex ( indexAfter ) ; return buffer ; } | Encode a simple UA TCP message . | 151 | 8 |
24,320 | public static void validateHostnameOrIpAddress ( X509Certificate certificate , String hostname ) throws UaException { boolean dnsNameMatches = validateSubjectAltNameField ( certificate , SUBJECT_ALT_NAME_DNS_NAME , hostname :: equals ) ; boolean ipAddressMatches = validateSubjectAltNameField ( certificate , SUBJECT_ALT_NAME_IP_ADDRESS , hostname :: equals ) ; if ( ! ( dnsNameMatches || ipAddressMatches ) ) { throw new UaException ( StatusCodes . Bad_CertificateHostNameInvalid ) ; } } | Validate that the hostname used in the endpoint URL matches either the SubjectAltName DNSName or IPAddress in the given certificate . | 130 | 28 |
24,321 | public static void validateApplicationUri ( X509Certificate certificate , String applicationUri ) throws UaException { if ( ! validateSubjectAltNameField ( certificate , SUBJECT_ALT_NAME_URI , applicationUri :: equals ) ) { throw new UaException ( StatusCodes . Bad_CertificateUriInvalid ) ; } } | Validate that the application URI matches the SubjectAltName URI in the given certificate . | 73 | 17 |
24,322 | public static byte [ ] hmac ( SecurityAlgorithm securityAlgorithm , byte [ ] secretKey , ByteBuffer ... buffers ) throws UaException { String transformation = securityAlgorithm . getTransformation ( ) ; try { Mac mac = Mac . getInstance ( transformation ) ; mac . init ( new SecretKeySpec ( secretKey , transformation ) ) ; for ( ByteBuffer buffer : buffers ) { mac . update ( buffer ) ; } return mac . doFinal ( ) ; } catch ( GeneralSecurityException e ) { throw new UaException ( StatusCodes . Bad_SecurityChecksFailed , e ) ; } } | Compute the HMAC of the provided buffers . | 130 | 10 |
24,323 | public static Optional < String [ ] > lookup ( long code ) { String [ ] desc = DESCRIPTIONS . get ( code & 0xFFFF0000 ) ; return Optional . ofNullable ( desc ) ; } | Lookup information about a StatusCode . | 45 | 8 |
24,324 | public static CompletableFuture < EndpointDescription [ ] > getEndpoints ( String endpointUrl ) { UaTcpStackClientConfig config = UaTcpStackClientConfig . builder ( ) . setEndpointUrl ( endpointUrl ) . build ( ) ; UaTcpStackClient client = new UaTcpStackClient ( config ) ; GetEndpointsRequest request = new GetEndpointsRequest ( new RequestHeader ( null , DateTime . now ( ) , uint ( 1 ) , uint ( 0 ) , null , uint ( 5000 ) , null ) , endpointUrl , null , new String [ ] { Stack . UA_TCP_BINARY_TRANSPORT_URI } ) ; return client . < GetEndpointsResponse > sendRequest ( request ) . whenComplete ( ( r , ex ) -> client . disconnect ( ) ) . thenApply ( GetEndpointsResponse :: getEndpoints ) ; } | Query the GetEndpoints service at the given endpoint URL . | 195 | 12 |
24,325 | protected void skipLinesAlreadyRead ( Iterator it ) { long linesRead = getItemsRead ( ) ; if ( linesRead > 0 ) { for ( long i = 0 ; i < linesRead ; i ++ ) { if ( it . hasNext ( ) ) { it . next ( ) ; } } } } | Skips the iterator ahead to the items read value stored in the execution context | 67 | 15 |
24,326 | protected void addToLong ( String key , long value ) { synchronized ( this . stepExecution ) { long currentValue = getLongValue ( key ) ; getExecutionContext ( ) . putLong ( key , currentValue + value ) ; } } | Adds the specified value to the existing key . | 53 | 9 |
24,327 | public void reload ( ) { try { if ( file . exists ( ) ) { try ( FileReader fileReader = new FileReader ( file ) ) { props . load ( fileReader ) ; } } } catch ( IOException e ) { FOKLogger . log ( Prefs . class . getName ( ) , Level . SEVERE , FOKLogger . DEFAULT_ERROR_TEXT , e ) ; } } | Reloads this preference file from the hard disk | 90 | 10 |
24,328 | public void setPreference ( String prefKey , String prefValue ) { props . setProperty ( prefKey , prefValue ) ; savePreferences ( ) ; } | Sets the value of the specified preference in the properties file | 34 | 12 |
24,329 | public String getPreference ( String prefKey , String defaultValue ) { return props . getProperty ( prefKey , defaultValue ) ; } | Returns the value of the specified preference . | 29 | 8 |
24,330 | protected Supplier < Set < Image > > overrideImageSupplier ( Injector injector , Supplier < Set < Image > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the image supplier | 39 | 11 |
24,331 | protected Supplier < Set < Location > > overrideLocationSupplier ( Injector injector , Supplier < Set < Location > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the location supplier | 39 | 11 |
24,332 | protected Supplier < Set < HardwareFlavor > > overrideHardwareFlavorSupplier ( Injector injector , Supplier < Set < HardwareFlavor > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the hardware supplier | 45 | 11 |
24,333 | protected Supplier < Set < VirtualMachine > > overrideVirtualMachineSupplier ( Injector injector , Supplier < Set < VirtualMachine > > originalSupplier ) { return originalSupplier ; } | Allows jclouds submodules to override the VirtualMachine supplier | 42 | 12 |
24,334 | public TemplateOptionsBuilder addOption ( Object field , Object value ) { additionalOptions . put ( field , value ) ; return this ; } | Adds a generic option to the template | 28 | 7 |
24,335 | public Location build ( ) { return new LocationImpl ( id , providerId , name , parent , isAssignable , locationScope , geoLocation , tags ) ; } | Builds the location . | 35 | 5 |
24,336 | public static String fromFile ( File file ) throws IOException { BufferedReader br = new BufferedReader ( new FileReader ( file ) ) ; StringBuilder sb = new StringBuilder ( ) ; String line = br . readLine ( ) ; while ( line != null ) { sb . append ( line ) ; line = br . readLine ( ) ; if ( line != null ) sb . append ( System . lineSeparator ( ) ) ; } br . close ( ) ; return sb . toString ( ) ; } | Reads the text from a text file | 114 | 8 |
24,337 | private static String getRequiredSpaces ( String reference , String message ) { StringBuilder res = new StringBuilder ( ) ; int requiredSpaces = reference . length ( ) - message . length ( ) - 4 ; for ( int i = 0 ; i < requiredSpaces ; i ++ ) { res . append ( " " ) ; } return res . toString ( ) ; } | Formats a message to be printed on the console | 79 | 10 |
24,338 | private void readRemoteConfig ( URL remoteConfig , URL fallbackConfig , boolean cacheRemoteConfig , String cacheFileName ) throws IOException { // Check if offline cache exists checkForOfflineCacheOrLoadFallback ( fallbackConfig , cacheFileName ) ; if ( ! isOfflineMode ( ) ) getRemoteConfig ( remoteConfig , cacheRemoteConfig , cacheFileName ) ; } | Reads the config from the remote url synchronously . If this fails for any reason and a cached config is available the cached config is used instead . If the remote config can t be read and no cached version is available the fallbackConfig is used . | 79 | 51 |
24,339 | public boolean contains ( String key ) { return onlineProps . getProperty ( key ) != null || offlineProps . getProperty ( key ) != null ; } | Checks if the specified key is defined in this Config file . | 34 | 13 |
24,340 | public void removeSnapshots ( ) { VersionList versionToRemove = new VersionList ( ) ; // collect Versions to be removed for ( Version ver : this ) { if ( ver . isSnapshot ( ) ) { versionToRemove . add ( ver ) ; } } // remove them this . removeAll ( versionToRemove ) ; } | Removes all snapshots from this list | 71 | 7 |
24,341 | public void markAsRead ( ) throws IOException , ClassNotFoundException { if ( ! this . isMarkedAsRead ( ) ) { FileOutputStream fileOut = getMotdFileOutputStreamProvider ( ) . createFileOutputStream ( getNextSerializationFileName ( ) ) ; ObjectOutputStream out = new ObjectOutputStream ( fileOut ) ; out . writeObject ( entry ) ; out . close ( ) ; fileOut . close ( ) ; } } | Marks this message of the day as read . | 98 | 10 |
24,342 | public boolean isValid ( ) { if ( name == null ) { return false ; } if ( type == null || ! type . isValid ( ) ) { return false ; } else if ( type == Type . Link ) { if ( url == null ) { return false ; } } // Check actions if ( this . getActions ( ) != null ) { for ( DesktopAction a : this . getActions ( ) ) { if ( ! a . isValid ( ) ) { return false ; } } } // Everything ok return true ; } | Checks if this link is valid to be saved | 114 | 10 |
24,343 | public List < Classification > list ( String classificationName ) { assertArgumentNotNull ( "classificationName" , classificationName ) ; final String delimiter = GROUP_DELIMITER ; final String pureName ; final String groupName ; if ( classificationName . contains ( delimiter ) ) { // e.g. sea.land or maihamadb-sea.land pureName = Srl . substringFirstFront ( classificationName , delimiter ) ; // e.g. sea or maihamadb-sea groupName = Srl . substringFirstRear ( classificationName , delimiter ) ; // e.g. land } else { // e.g. sea or maihamadb-sea pureName = classificationName ; groupName = null ; } final ClassificationMeta meta = findClassificationMeta ( pureName , ( ) -> { return "list('" + classificationName + "')" ; } ) ; if ( groupName != null ) { final List < Classification > groupOfList = meta . groupOf ( groupName ) ; if ( groupOfList . isEmpty ( ) ) { // means not found throw new TemplateProcessingException ( "Not found the classification group: " + groupName + " of " + pureName ) ; } return groupOfList ; } else { return meta . listAll ( ) ; } } | Get list of specified classification . | 288 | 6 |
24,344 | public List < Classification > listAll ( String classificationName ) { assertArgumentNotNull ( "classificationName" , classificationName ) ; return findClassificationMeta ( classificationName , ( ) -> { return "listAll('" + classificationName + "')" ; } ) . listAll ( ) ; } | Get list of all classification . | 65 | 6 |
24,345 | public String alias ( Object cls , String defaultValue ) { assertArgumentNotNull ( "defaultValue" , defaultValue ) ; if ( cls != null ) { return alias ( cls ) ; } else { return defaultValue ; } } | Get classification alias or default value if the classification is null . | 52 | 12 |
24,346 | public Classification codeOf ( String classificationName , String code ) { assertArgumentNotNull ( "elementName" , classificationName ) ; assertArgumentNotNull ( "code" , code ) ; return findClassificationMeta ( classificationName , ( ) -> { return "codeOf('" + classificationName + "', '" + code + "')" ; } ) . codeOf ( code ) ; } | Get classification by code . | 85 | 5 |
24,347 | public Classification nameOf ( String classificationName , String name ) { return findClassificationMeta ( ( String ) classificationName , ( ) -> { return "nameOf('" + classificationName + "', '" + name + "')" ; } ) . nameOf ( name ) ; } | Get classification by name . | 60 | 5 |
24,348 | @ Nullable @ Override public T get ( String s ) { checkNotNull ( s ) ; checkArgument ( ! s . isEmpty ( ) ) ; for ( T t : supplier . get ( ) ) { if ( t . id ( ) . equals ( s ) ) { return t ; } } return null ; } | Searches for the given id in the supplier . | 69 | 11 |
24,349 | public static UpdateInfo isUpdateAvailable ( URL repoBaseURL , String mavenGroupID , String mavenArtifactID , String mavenClassifier ) { return isUpdateAvailable ( repoBaseURL , mavenGroupID , mavenArtifactID , mavenClassifier , "jar" ) ; } | Checks if a new release has been published on the website . This does not compare the current app version to the release version on the website just checks if something happened on the website . This ensures that updates that were ignored by the user do not show up again . Assumes that the artifact has a jar - packaging . | 64 | 64 |
24,350 | @ SuppressWarnings ( "Duplicates" ) public static UpdateInfo isUpdateAvailable ( URL repoBaseURL , String mavenGroupID , String mavenArtifactID , String mavenClassifier , @ SuppressWarnings ( "SameParameterValue" ) String packaging ) { String savedSetting = updatePrefs . getPreference ( latestSeenVersionPrefKey , "" ) ; UpdateInfo res = null ; try { FOKLogger . info ( UpdateChecker . class . getName ( ) , "Checking for updates..." ) ; res = getLatestUpdateInfo ( repoBaseURL , mavenGroupID , mavenArtifactID , mavenClassifier , packaging ) ; Version currentVersion ; try { currentVersion = new Version ( Common . getInstance ( ) . getAppVersion ( ) ) ; } catch ( IllegalArgumentException e ) { FOKLogger . log ( UpdateChecker . class . getName ( ) , Level . SEVERE , FOKLogger . DEFAULT_ERROR_TEXT , e ) ; res . showAlert = false ; return res ; } Version savedVersion ; try { savedVersion = new Version ( savedSetting ) ; } catch ( IllegalArgumentException e ) { // No update was ever ignored by the user so use the current // version as the savedVersion savedVersion = currentVersion ; } if ( res . toVersion . compareTo ( savedVersion ) > 0 ) { // new update found FOKLogger . info ( UpdateChecker . class . getName ( ) , "Update available!" ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Version after update: " + res . toVersion . toString ( ) ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Filesize: " + res . fileSizeInMB + "MB" ) ; res . showAlert = true ; } else if ( res . toVersion . compareTo ( currentVersion ) > 0 ) { // found update that is ignored FOKLogger . info ( UpdateChecker . class . getName ( ) , "Update available (Update was ignored by the user)!" ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Version after update: " + res . toVersion . toString ( ) ) ; FOKLogger . info ( UpdateChecker . class . getName ( ) , "Filesize: " + res . fileSizeInMB + "MB" ) ; } else { FOKLogger . info ( UpdateChecker . class . getName ( ) , "No update found." ) ; } } catch ( JDOMException | IOException e ) { FOKLogger . log ( UpdateChecker . class . getName ( ) , Level . SEVERE , FOKLogger . DEFAULT_ERROR_TEXT , e ) ; } return res ; } | Checks if a new release has been published on the website . This does not compare the current app version to the release version on the website just checks if something happened on the website . This ensures that updates that were ignored by the user do not show up again . | 624 | 53 |
24,351 | public static UpdateInfo isUpdateAvailableCompareAppVersion ( URL repoBaseURL , String mavenGroupID , String mavenArtifactID , String mavenClassifier ) { return isUpdateAvailableCompareAppVersion ( repoBaseURL , mavenGroupID , mavenArtifactID , mavenClassifier , "jar" ) ; } | Checks if a new release has been published on the website . This compares the current appVersion to the version available on the website and thus does not take into account if the user ignored that update . Assumes that the artifact has a jar - packaging . | 70 | 51 |
24,352 | protected void checkRegisteredDataUsingReservedWord ( ActionRuntime runtime , WebContext context , String varKey ) { if ( isSuppressRegisteredDataUsingReservedWordCheck ( ) ) { return ; } if ( context . getVariableNames ( ) . contains ( varKey ) ) { throwThymeleafRegisteredDataUsingReservedWordException ( runtime , context , varKey ) ; } } | Thymeleaf s reserved words are already checked in Thymeleaf process so no check them here | 82 | 20 |
24,353 | @ ApiModelProperty ( required = true , value = "Primary account number that uniquely identifies this card." ) @ JsonProperty ( "pan" ) @ NotNull @ Pattern ( regexp = "[0-9]{1,19}" ) @ Masked public String getPan ( ) { return pan ; } | Primary account number that uniquely identifies this card . | 66 | 9 |
24,354 | @ Path ( "{snapshotId}/complete" ) @ POST @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response complete ( @ PathParam ( "snapshotId" ) String snapshotId , CompleteSnapshotBridgeParameters params ) { try { Snapshot snapshot = this . snapshotRepo . findByName ( snapshotId ) ; // parse alternate IDs if provided List < String > alternateIds = params . getAlternateIds ( ) ; String altIds = "[]" ; if ( alternateIds != null && ! alternateIds . isEmpty ( ) ) { // add alternate IDs to snapshot snapshot = this . snapshotManager . addAlternateSnapshotIds ( snapshot , alternateIds ) ; // build alternate IDs for history StringBuilder history = new StringBuilder ( ) ; history . append ( "[" ) ; boolean first = true ; for ( String id : alternateIds ) { if ( ! first ) { history . append ( "," ) ; } history . append ( "'" + id + "'" ) ; first = false ; } history . append ( "]" ) ; altIds = history . toString ( ) ; } // Add history event String history = "[{'" + SNAPSHOT_ACTION_TITLE + "':'" + SNAPSHOT_ACTION_COMPLETED + "'}," + "{'" + SNAPSHOT_ID_TITLE + "':'" + snapshotId + "'}," + "{'" + SNAPSHOT_ALT_IDS_TITLE + "':" + altIds + "}]" ; snapshotManager . updateHistory ( snapshot , history ) ; snapshot = this . snapshotManager . transferToStorageComplete ( snapshotId ) ; log . info ( "successfully processed snapshot complete notification: {}" , snapshot ) ; return Response . ok ( null ) . entity ( new CompleteSnapshotBridgeResult ( snapshot . getStatus ( ) , snapshot . getStatusText ( ) ) ) . build ( ) ; } catch ( AlternateIdAlreadyExistsException ex ) { log . warn ( ex . getMessage ( ) ) ; return Response . status ( HttpStatus . SC_BAD_REQUEST ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } catch ( Exception ex ) { log . error ( ex . getMessage ( ) , ex ) ; return Response . serverError ( ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } } | Notifies the bridge that the snapshot transfer from the bridge storage to the preservation storage is complete . Also sets a snapshot s alternate id s if they are passed in . | 532 | 33 |
24,355 | @ Path ( "{snapshotId}/error" ) @ POST @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response error ( @ PathParam ( "snapshotId" ) String snapshotId , SnapshotErrorBridgeParameters params ) { try { Snapshot snapshot = snapshotManager . transferError ( snapshotId , params . getError ( ) ) ; log . info ( "Processed snapshot error notification: {}" , snapshot ) ; return Response . ok ( new SnapshotErrorBridgeResult ( snapshot . getStatus ( ) , snapshot . getStatusText ( ) ) ) . build ( ) ; } catch ( Exception ex ) { log . error ( ex . getMessage ( ) , ex ) ; return Response . serverError ( ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } } | Notifies the bridge that the snapshot process is not able to continue due to an error which cannot be resolved by the system processing the snapshot data . | 187 | 29 |
24,356 | @ Path ( "{snapshotId}/history" ) @ POST @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updateHistory ( @ PathParam ( "snapshotId" ) String snapshotId , UpdateSnapshotHistoryBridgeParameters params ) { try { if ( params . getAlternate ( ) == null ) { return Response . serverError ( ) . entity ( new ResponseDetails ( "Incorrect parameters submitted!" ) ) . build ( ) ; } Snapshot snapshot = ( params . getAlternate ( ) ? this . snapshotRepo . findBySnapshotAlternateIds ( snapshotId ) : this . snapshotRepo . findByName ( snapshotId ) ) ; // sanity check to make sure snapshot exists if ( snapshot != null ) { // sanity check input from history if ( params . getHistory ( ) != null && params . getHistory ( ) . length ( ) > 0 ) { // set history, and refresh our variable from the DB snapshot = this . snapshotManager . updateHistory ( snapshot , params . getHistory ( ) ) ; log . info ( "successfully processed snapshot " + "history update: {}" , snapshot ) ; } else { log . info ( "did not process empty or null snapshot " + "history update: {}" , snapshot ) ; } SnapshotSummary snapSummary = createSnapshotSummary ( snapshot ) ; List < SnapshotHistory > snapMeta = snapshot . getSnapshotHistory ( ) ; String history = // retrieve latest history update ( ( snapMeta != null && snapMeta . size ( ) > 0 ) ? snapMeta . get ( snapMeta . size ( ) - 1 ) . getHistory ( ) : "" ) ; UpdateSnapshotHistoryBridgeResult result = new UpdateSnapshotHistoryBridgeResult ( snapSummary , history ) ; log . debug ( "Returning results of update snapshot history: {}" , result ) ; return Response . ok ( null ) . entity ( result ) . build ( ) ; } else { String error = "Snapshot with " + ( params . getAlternate ( ) ? "alternate " : "" ) + "id [" + snapshotId + "] not found!" ; return Response . serverError ( ) . entity ( new ResponseDetails ( error ) ) . build ( ) ; } } catch ( Exception ex ) { log . error ( ex . getMessage ( ) , ex ) ; return Response . serverError ( ) . entity ( new ResponseDetails ( ex . getMessage ( ) ) ) . build ( ) ; } } | Updates a snapshot s history | 534 | 6 |
24,357 | @ Override public void onWriteError ( Exception e , List < ? extends ContentItem > items ) { StringBuilder sb = new StringBuilder ( ) ; for ( ContentItem item : items ) { sb . append ( item . getContentId ( ) + ", " ) ; } String message = "Error writing item(s): " + e . getMessage ( ) + ": items=" + sb . toString ( ) ; this . errors . add ( message ) ; log . error ( message , e ) ; } | Method defined in ItemWriteListener interface | 111 | 7 |
24,358 | private Date changeRestoreStatus ( Restoration restoration , RestoreStatus status , String msg , Date currentDate ) { log . info ( "Changing restore status to: " + status + " with message: " + msg ) ; restoration . setStatus ( status ) ; restoration . setStatusText ( msg ) ; Date expirationDate = getExpirationDate ( currentDate , daysToExpire ) ; if ( status . equals ( RestoreStatus . RESTORATION_COMPLETE ) ) { restoration . setEndDate ( currentDate ) ; restoration . setExpirationDate ( expirationDate ) ; } restoreRepo . save ( restoration ) ; eventLog . logRestoreUpdate ( restoration ) ; return expirationDate ; } | Updates the restore details in the database | 145 | 8 |
24,359 | protected Date getExpirationDate ( Date endDate , int daysToExpire ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( endDate ) ; calendar . add ( Calendar . DATE , daysToExpire ) ; return calendar . getTime ( ) ; } | Calculates the restore expiration date based on the restoration end date and the number of days before retirement | 61 | 20 |
24,360 | private SnapshotTaskClient getSnapshotTaskClient ( DuracloudEndPointConfig source ) { return this . snapshotTaskClientHelper . create ( source , bridgeConfig . getDuracloudUsername ( ) , bridgeConfig . getDuracloudPassword ( ) ) ; } | Build the snapshot task client - for communicating with the DuraCloud snapshot provider to perform tasks . | 57 | 19 |
24,361 | @ SuppressWarnings ( "UnusedReturnValue" ) public static String webread ( URL url ) throws IOException { StringBuilder result = new StringBuilder ( ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( "GET" ) ; BufferedReader rd = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ; String line ; while ( ( line = rd . readLine ( ) ) != null ) { result . append ( line ) ; } rd . close ( ) ; return result . toString ( ) ; } | Sends a GET request to url and retrieves the server response | 137 | 13 |
24,362 | public static void openInDefaultBrowser ( URL url ) throws IOException { Runtime rt = Runtime . getRuntime ( ) ; if ( SystemUtils . IS_OS_WINDOWS ) { rt . exec ( "rundll32 url.dll,FileProtocolHandler " + url ) ; } else if ( SystemUtils . IS_OS_MAC ) { rt . exec ( "open" + url ) ; } else { String [ ] browsers = { "epiphany" , "firefox" , "mozilla" , "konqueror" , "netscape" , "opera" , "links" , "lynx" } ; StringBuilder cmd = new StringBuilder ( ) ; for ( int i = 0 ; i < browsers . length ; i ++ ) cmd . append ( i == 0 ? "" : " || " ) . append ( browsers [ i ] ) . append ( " \"" ) . append ( url ) . append ( "\" " ) ; rt . exec ( new String [ ] { "sh" , "-c" , cmd . toString ( ) } ) ; } } | OPens the specified url in the default browser . | 237 | 10 |
24,363 | public String format ( Object expression , Object objPattern ) { if ( objPattern instanceof String ) { final String pattern = filterPattern ( ( String ) objPattern ) ; if ( expression == null ) { return null ; } if ( expression instanceof LocalDate ) { return create ( ( LocalDate ) expression ) . toDisp ( pattern ) ; } if ( expression instanceof LocalDateTime ) { return create ( ( LocalDateTime ) expression ) . toDisp ( pattern ) ; } if ( expression instanceof java . util . Date ) { return create ( ( java . util . Date ) expression ) . toDisp ( pattern ) ; } if ( expression instanceof String ) { return create ( ( String ) expression ) . toDisp ( pattern ) ; } String msg = "First argument as two arguments should be LocalDate or LocalDateTime or Date or String(expression): " + expression ; throw new TemplateProcessingException ( msg ) ; } String msg = "Second argument as two arguments should be String(pattern): objPattern=" + objPattern ; throw new TemplateProcessingException ( msg ) ; } | Get formatted date string . | 232 | 5 |
24,364 | private NodeMetadata enrich ( NodeMetadata nodeMetadata , Template template ) { final NodeMetadataBuilder nodeMetadataBuilder = NodeMetadataBuilder . fromNodeMetadata ( nodeMetadata ) ; if ( nodeMetadata . getHardware ( ) == null ) { nodeMetadataBuilder . hardware ( template . getHardware ( ) ) ; } if ( nodeMetadata . getImageId ( ) == null ) { nodeMetadataBuilder . imageId ( template . getImage ( ) . getId ( ) ) ; } if ( nodeMetadata . getLocation ( ) == null ) { nodeMetadataBuilder . location ( template . getLocation ( ) ) ; } return nodeMetadataBuilder . build ( ) ; } | Enriches the spawned vm with information of the template if the spawned vm does not contain information about hardware image or location | 150 | 24 |
24,365 | protected org . jclouds . compute . options . TemplateOptions modifyTemplateOptions ( VirtualMachineTemplate originalVirtualMachineTemplate , org . jclouds . compute . options . TemplateOptions originalTemplateOptions ) { return originalTemplateOptions ; } | Extension point for the template options . Allows the subclass to replace the jclouds template options object with a new one before it is passed to the template builder . | 48 | 33 |
24,366 | public boolean verify ( ) { this . errors = new LinkedList <> ( ) ; try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( generator . generate ( spaceId , ManifestFormat . TSV ) ) ) ) { WriteOnlyStringSet snapshotManifest = ManifestFileHelper . loadManifestSetFromFile ( this . md5Manifest ) ; log . info ( "loaded manifest set into memory." ) ; ManifestFormatter formatter = new TsvManifestFormatter ( ) ; // skip header if ( formatter . getHeader ( ) != null ) { reader . readLine ( ) ; } String line = null ; int stitchedManifestCount = 0 ; while ( ( line = reader . readLine ( ) ) != null ) { ManifestItem item = formatter . parseLine ( line ) ; String contentId = item . getContentId ( ) ; if ( ! contentId . equals ( Constants . SNAPSHOT_PROPS_FILENAME ) ) { if ( ! snapshotManifest . contains ( ManifestFileHelper . formatManifestSetString ( contentId , item . getContentChecksum ( ) ) ) ) { String message = "Snapshot manifest does not contain content id/checksum combination (" + contentId + ", " + item . getContentChecksum ( ) ; errors . add ( message ) ; } stitchedManifestCount ++ ; } } int snapshotCount = snapshotManifest . size ( ) ; if ( stitchedManifestCount != snapshotCount ) { String message = "Snapshot Manifest size (" + snapshotCount + ") does not equal DuraCloud Manifest (" + stitchedManifestCount + ")" ; errors . add ( message ) ; log . error ( message ) ; } } catch ( Exception e ) { String message = "Failed to verify space manifest against snapshot manifest:" + e . getMessage ( ) ; errors . add ( message ) ; log . error ( message , e ) ; } log . info ( "verification complete. error count = {}" , errors . size ( ) ) ; return getResult ( errors ) ; } | Performs the verification . | 446 | 5 |
24,367 | @ Nullable private static Identifiers handleIdentifiers ( String domainIdOrName , String projectIdOrName , String endpoint , String userId , String password ) { //we try all four cases and return the one that works Set < Identifiers > possibleIdentifiers = new HashSet < Identifiers > ( ) { { add ( new Identifiers ( Identifier . byName ( domainIdOrName ) , Identifier . byName ( projectIdOrName ) ) ) ; add ( new Identifiers ( Identifier . byId ( domainIdOrName ) , Identifier . byId ( projectIdOrName ) ) ) ; add ( new Identifiers ( Identifier . byId ( domainIdOrName ) , Identifier . byName ( projectIdOrName ) ) ) ; add ( new Identifiers ( Identifier . byName ( domainIdOrName ) , Identifier . byId ( projectIdOrName ) ) ) ; } } ; for ( Identifiers candidate : possibleIdentifiers ) { try { authenticate ( endpoint , userId , password , candidate . getDomain ( ) , candidate . getProject ( ) ) ; } catch ( AuthenticationException | ClientResponseException e ) { continue ; } return candidate ; } return null ; } | This method tries to determine if the authentication should happen by using the user provided information as domain ID or domain name resp . project ID or project name . | 258 | 30 |
24,368 | @ Override protected void configure ( ) { bind ( DiscoveryService . class ) . to ( BaseDiscoveryService . class ) ; bind ( OperatingSystemDetectionStrategy . class ) . to ( NameSubstringBasedOperatingSystemDetectionStrategy . class ) ; } | Can be extended to load own implementation of classes . | 57 | 10 |
24,369 | public static Update update ( String key , Object value ) { return new Update ( ) . set ( key , value ) ; } | Static factory method to create an Update using the provided key | 26 | 11 |
24,370 | public static void encryptFields ( Object object , CollectionMetaData cmd , ICipher cipher ) throws IllegalAccessException , IllegalArgumentException , InvocationTargetException { for ( String secretAnnotatedFieldName : cmd . getSecretAnnotatedFieldNames ( ) ) { Method getterMethod = cmd . getGetterMethodForFieldName ( secretAnnotatedFieldName ) ; Method setterMethod = cmd . getSetterMethodForFieldName ( secretAnnotatedFieldName ) ; String value ; String encryptedValue = null ; try { value = ( String ) getterMethod . invoke ( object ) ; if ( null != value ) { encryptedValue = cipher . encrypt ( value ) ; setterMethod . invoke ( object , encryptedValue ) ; } } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { logger . error ( "Error when invoking method for a @Secret annotated field" , e ) ; throw e ; } } } | A utility method to encrypt the value of field marked by the | 204 | 12 |
24,371 | public static void decryptFields ( Object object , CollectionMetaData cmd , ICipher cipher ) throws IllegalAccessException , IllegalArgumentException , InvocationTargetException { for ( String secretAnnotatedFieldName : cmd . getSecretAnnotatedFieldNames ( ) ) { Method getterMethod = cmd . getGetterMethodForFieldName ( secretAnnotatedFieldName ) ; Method setterMethod = cmd . getSetterMethodForFieldName ( secretAnnotatedFieldName ) ; String value ; String decryptedValue = null ; try { value = ( String ) getterMethod . invoke ( object ) ; if ( null != value ) { decryptedValue = cipher . decrypt ( value ) ; setterMethod . invoke ( object , decryptedValue ) ; } } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { logger . error ( "Error when invoking method for a @Secret annotated field" , e ) ; throw e ; } } } | A utility method to decrypt the value of field marked by the | 207 | 12 |
24,372 | public static String generate128BitKey ( String password , String salt ) throws NoSuchAlgorithmException , UnsupportedEncodingException , InvalidKeySpecException { SecretKeyFactory factory = SecretKeyFactory . getInstance ( "PBKDF2WithHmacSHA256" ) ; KeySpec spec = new PBEKeySpec ( password . toCharArray ( ) , salt . getBytes ( ) , 65536 , 128 ) ; SecretKey key = factory . generateSecret ( spec ) ; byte [ ] keybyte = key . getEncoded ( ) ; return Base64 . getEncoder ( ) . encodeToString ( keybyte ) ; } | Utility method to help generate a strong 128 bit Key to be used for the DefaultAESCBCCipher . | 133 | 23 |
24,373 | public static CollectionSchemaUpdate update ( String key , IOperation operation ) { return new CollectionSchemaUpdate ( ) . set ( key , operation ) ; } | Static factory method to create an CollectionUpdate for the specified key | 33 | 12 |
24,374 | public CollectionSchemaUpdate set ( String key , IOperation operation ) { collectionUpdateData . put ( key , operation ) ; return this ; } | A method to set a new Operation for a key . It may be of type ADD RENAME or DELETE . Only one operation per key can be specified . Attempt to add a second operation for a any key will override the first one . Attempt to add a ADD operation for a key which already exists will have no effect . Attempt to add a DELETE operation for akey which does not exist will have no effect . | 30 | 87 |
24,375 | public Map < String , AddOperation > getAddOperations ( ) { Map < String , AddOperation > addOperations = new TreeMap < String , AddOperation > ( ) ; for ( Entry < String , IOperation > entry : collectionUpdateData . entrySet ( ) ) { String key = entry . getKey ( ) ; IOperation op = entry . getValue ( ) ; if ( op . getOperationType ( ) . equals ( Type . ADD ) ) { AddOperation aop = ( AddOperation ) op ; if ( null != aop . getDefaultValue ( ) ) { addOperations . put ( key , aop ) ; } } } return addOperations ; } | Returns a Map of ADD operations which have a non - null default value specified . | 144 | 16 |
24,376 | public Map < String , RenameOperation > getRenameOperations ( ) { Map < String , RenameOperation > renOperations = new TreeMap < String , RenameOperation > ( ) ; for ( Entry < String , IOperation > entry : collectionUpdateData . entrySet ( ) ) { String key = entry . getKey ( ) ; IOperation op = entry . getValue ( ) ; if ( op . getOperationType ( ) . equals ( Type . RENAME ) ) { renOperations . put ( key , ( RenameOperation ) op ) ; } } return renOperations ; } | Returns a Map of RENAME operations . | 128 | 9 |
24,377 | public Map < String , DeleteOperation > getDeleteOperations ( ) { Map < String , DeleteOperation > delOperations = new TreeMap < String , DeleteOperation > ( ) ; for ( Entry < String , IOperation > entry : collectionUpdateData . entrySet ( ) ) { String key = entry . getKey ( ) ; IOperation op = entry . getValue ( ) ; if ( op . getOperationType ( ) . equals ( Type . DELETE ) ) { delOperations . put ( key , ( DeleteOperation ) op ) ; } } return delOperations ; } | Returns a Map of DELETE operations . | 123 | 9 |
24,378 | protected static Object getIdForEntity ( Object document , Method getterMethodForId ) { Object id = null ; if ( null != getterMethodForId ) { try { id = getterMethodForId . invoke ( document ) ; } catch ( IllegalAccessException e ) { logger . error ( "Failed to invoke getter method for a idAnnotated field due to permissions" , e ) ; throw new InvalidJsonDbApiUsageException ( "Failed to invoke getter method for a idAnnotated field due to permissions" , e ) ; } catch ( IllegalArgumentException e ) { logger . error ( "Failed to invoke getter method for a idAnnotated field due to wrong arguments" , e ) ; throw new InvalidJsonDbApiUsageException ( "Failed to invoke getter method for a idAnnotated field due to wrong arguments" , e ) ; } catch ( InvocationTargetException e ) { logger . error ( "Failed to invoke getter method for a idAnnotated field, the method threw a exception" , e ) ; throw new InvalidJsonDbApiUsageException ( "Failed to invoke getter method for a idAnnotated field, the method threw a exception" , e ) ; } } return id ; } | A utility method to extract the value of field marked by the | 276 | 12 |
24,379 | protected static Object deepCopy ( Object fromBean ) { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; XMLEncoder out = new XMLEncoder ( bos ) ; out . writeObject ( fromBean ) ; out . close ( ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; XMLDecoder in = new XMLDecoder ( bis , null , null , JsonDBTemplate . class . getClassLoader ( ) ) ; Object toBean = in . readObject ( ) ; in . close ( ) ; return toBean ; } | A utility method that creates a deep clone of the specified object . There is no other way of doing this reliably . | 134 | 23 |
24,380 | public static boolean stampVersion ( JsonDBConfig dbConfig , File f , String version ) { FileOutputStream fos = null ; OutputStreamWriter osr = null ; BufferedWriter writer = null ; try { fos = new FileOutputStream ( f ) ; osr = new OutputStreamWriter ( fos , dbConfig . getCharset ( ) ) ; writer = new BufferedWriter ( osr ) ; String versionData = dbConfig . getObjectMapper ( ) . writeValueAsString ( new SchemaVersion ( version ) ) ; writer . write ( versionData ) ; writer . newLine ( ) ; } catch ( JsonProcessingException e ) { logger . error ( "Failed to serialize SchemaVersion to Json string" , e ) ; return false ; } catch ( IOException e ) { logger . error ( "Failed to write SchemaVersion to the new .json file {}" , f , e ) ; return false ; } finally { try { writer . close ( ) ; } catch ( IOException e ) { logger . error ( "Failed to close BufferedWriter for new collection file {}" , f , e ) ; } try { osr . close ( ) ; } catch ( IOException e ) { logger . error ( "Failed to close OutputStreamWriter for new collection file {}" , f , e ) ; } try { fos . close ( ) ; } catch ( IOException e ) { logger . error ( "Failed to close FileOutputStream for new collection file {}" , f , e ) ; } } return true ; } | Utility to stamp the version into a newly created . json File This method is expected to be invoked on a newly created . json file before it is usable . So no locking code required . | 340 | 38 |
24,381 | @ Override public String decrypt ( String cipherText ) { this . decryptionLock . lock ( ) ; try { String decryptedValue = null ; try { byte [ ] bytes = Base64 . getDecoder ( ) . decode ( cipherText ) ; decryptedValue = new String ( decryptCipher . doFinal ( bytes ) , charset ) ; } catch ( UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e ) { logger . error ( "DefaultAESCBCCipher failed to decrypt text" , e ) ; throw new JsonDBException ( "DefaultAESCBCCipher failed to decrypt text" , e ) ; } return decryptedValue ; } finally { this . decryptionLock . unlock ( ) ; } } | A method to decrypt the provided cipher text . | 159 | 9 |
24,382 | @ Override public int compare ( String expected , String actual ) { String [ ] vals1 = expected . split ( "\\." ) ; String [ ] vals2 = actual . split ( "\\." ) ; int i = 0 ; while ( i < vals1 . length && i < vals2 . length && vals1 [ i ] . equals ( vals2 [ i ] ) ) { i ++ ; } if ( i < vals1 . length && i < vals2 . length ) { int diff = Integer . valueOf ( vals1 [ i ] ) . compareTo ( Integer . valueOf ( vals2 [ i ] ) ) ; return Integer . signum ( diff ) ; } else { return Integer . signum ( vals1 . length - vals2 . length ) ; } } | compare the expected version with the actual version . | 176 | 10 |
24,383 | public static Keyword keyword ( Object o ) { if ( o instanceof Keyword ) return ( Keyword ) o ; else if ( o instanceof String ) { String s = ( String ) o ; if ( s . charAt ( 0 ) == ' ' ) return new KeywordImpl ( s . substring ( 1 ) ) ; else return new KeywordImpl ( s ) ; } else throw new IllegalArgumentException ( "Cannot make keyword from " + o . getClass ( ) . getSimpleName ( ) ) ; } | Converts a string or keyword to a keyword | 112 | 9 |
24,384 | public static Symbol symbol ( Object o ) { if ( o instanceof Symbol ) return ( Symbol ) o ; else if ( o instanceof String ) { String s = ( String ) o ; if ( s . charAt ( 0 ) == ' ' ) return new SymbolImpl ( s . substring ( 1 ) ) ; else return new SymbolImpl ( s ) ; } else throw new IllegalArgumentException ( "Cannot make symbol from " + o . getClass ( ) . getSimpleName ( ) ) ; } | Converts a string or a symbol to a symbol | 107 | 10 |
24,385 | public static < T > TaggedValue < T > taggedValue ( String tag , T rep ) { return new TaggedValueImpl < T > ( tag , rep ) ; } | Creates a TaggedValue | 37 | 6 |
24,386 | private long readNumber ( int firstChar , boolean isNeg ) throws IOException { out . unsafeWrite ( firstChar ) ; // unsafe OK since we know output is big enough // We build up the number in the negative plane since it's larger (by one) than // the positive plane. long v = ' ' - firstChar ; // can't overflow a long in 18 decimal digits (i.e. 17 additional after the first). // we also need 22 additional to handle double so we'll handle in 2 separate loops. int i ; for ( i = 0 ; i < 17 ; i ++ ) { int ch = getChar ( ) ; // TODO: is this switch faster as an if-then-else? switch ( ch ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : v = v * 10 - ( ch - ' ' ) ; out . unsafeWrite ( ch ) ; continue ; case ' ' : out . unsafeWrite ( ' ' ) ; valstate = readFrac ( out , 22 - i ) ; return 0 ; case ' ' : case ' ' : out . unsafeWrite ( ch ) ; nstate = 0 ; valstate = readExp ( out , 22 - i ) ; return 0 ; default : // return the number, relying on nextEvent() to return an error // for invalid chars following the number. if ( ch != - 1 ) -- start ; // push back last char if not EOF valstate = LONG ; return isNeg ? v : - v ; } } // after this, we could overflow a long and need to do extra checking boolean overflow = false ; long maxval = isNeg ? Long . MIN_VALUE : - Long . MAX_VALUE ; for ( ; i < 22 ; i ++ ) { int ch = getChar ( ) ; switch ( ch ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : if ( v < ( 0x8000000000000000 L / 10 ) ) overflow = true ; // can't multiply by 10 w/o overflowing v *= 10 ; int digit = ch - ' ' ; if ( v < maxval + digit ) overflow = true ; // can't add digit w/o overflowing v -= digit ; out . unsafeWrite ( ch ) ; continue ; case ' ' : out . unsafeWrite ( ' ' ) ; valstate = readFrac ( out , 22 - i ) ; return 0 ; case ' ' : case ' ' : out . unsafeWrite ( ch ) ; nstate = 0 ; valstate = readExp ( out , 22 - i ) ; return 0 ; default : // return the number, relying on nextEvent() to return an error // for invalid chars following the number. if ( ch != - 1 ) -- start ; // push back last char if not EOF valstate = overflow ? BIGNUMBER : LONG ; return isNeg ? v : - v ; } } nstate = 0 ; valstate = BIGNUMBER ; return 0 ; } | Returns the long read ... only significant if valstate == LONG after this call . firstChar should be the first numeric digit read . | 675 | 26 |
24,387 | private int readFrac ( CharArr arr , int lim ) throws IOException { nstate = HAS_FRACTION ; // deliberate set instead of '|' while ( -- lim >= 0 ) { int ch = getChar ( ) ; if ( ch >= ' ' && ch <= ' ' ) { arr . write ( ch ) ; } else if ( ch == ' ' || ch == ' ' ) { arr . write ( ch ) ; return readExp ( arr , lim ) ; } else { if ( ch != - 1 ) start -- ; // back up return NUMBER ; } } return BIGNUMBER ; } | read digits right of decimal point | 130 | 6 |
24,388 | private int readExp ( CharArr arr , int lim ) throws IOException { nstate |= HAS_EXPONENT ; int ch = getChar ( ) ; lim -- ; if ( ch == ' ' || ch == ' ' ) { arr . write ( ch ) ; ch = getChar ( ) ; lim -- ; } // make sure at least one digit is read. if ( ch < ' ' || ch > ' ' ) { throw err ( "missing exponent number" ) ; } arr . write ( ch ) ; return readExpDigits ( arr , lim ) ; } | call after e or E has been seen to read the rest of the exponent | 122 | 15 |
24,389 | private int readExpDigits ( CharArr arr , int lim ) throws IOException { while ( -- lim >= 0 ) { int ch = getChar ( ) ; if ( ch >= ' ' && ch <= ' ' ) { arr . write ( ch ) ; } else { if ( ch != - 1 ) start -- ; // back up return NUMBER ; } } return BIGNUMBER ; } | continuation of readExpStart | 84 | 6 |
24,390 | private char readEscapedChar ( ) throws IOException { int ch = getChar ( ) ; switch ( ch ) { case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ( char ) ( ( hexval ( getChar ( ) ) << 12 ) | ( hexval ( getChar ( ) ) << 8 ) | ( hexval ( getChar ( ) ) << 4 ) | ( hexval ( getChar ( ) ) ) ) ; } if ( ( flags & ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER ) != 0 && ch != EOF ) { return ( char ) ch ; } throw err ( "Invalid character escape" ) ; } | backslash has already been read when this is called | 207 | 11 |
24,391 | private void readStringChars2 ( CharArr arr , int middle ) throws IOException { if ( stringTerm == 0 ) { readStringBare ( arr ) ; return ; } char terminator = ( char ) stringTerm ; for ( ; ; ) { if ( middle >= end ) { arr . write ( buf , start , middle - start ) ; start = middle ; getMore ( ) ; middle = start ; } int ch = buf [ middle ++ ] ; if ( ch == terminator ) { int len = middle - start - 1 ; if ( len > 0 ) arr . write ( buf , start , len ) ; start = middle ; return ; } else if ( ch == ' ' ) { int len = middle - start - 1 ; if ( len > 0 ) arr . write ( buf , start , len ) ; start = middle ; arr . write ( readEscapedChar ( ) ) ; middle = start ; } } } | this should be faster for strings with fewer escapes but probably slower for many escapes . | 197 | 16 |
24,392 | public void getNumberChars ( CharArr output ) throws IOException { int ev = 0 ; if ( valstate == 0 ) ev = nextEvent ( ) ; if ( valstate == LONG || valstate == NUMBER ) output . write ( this . out ) ; else if ( valstate == BIGNUMBER ) { continueNumber ( output ) ; } else { throw err ( "Unexpected " + ev ) ; } valstate = 0 ; } | Reads a JSON numeric value into the output . | 96 | 10 |
24,393 | public long parseLong ( char [ ] arr , int start , int end ) { long x = 0 ; boolean negative = arr [ start ] == ' ' ; for ( int i = negative ? start + 1 : start ; i < end ; i ++ ) { // If constructing the largest negative number, this will overflow // to the largest negative number. This is OK since the negation of // the largest negative number is itself in two's complement. x = x * 10 + ( arr [ i ] - ' ' ) ; } // could replace conditional-move with multiplication of sign... not sure // which is faster. return negative ? - x : x ; } | belongs in number utils or charutil? | 136 | 10 |
24,394 | protected SocketFactory createSocketFactory ( InetAddress address , int port , InetAddress localAddr , int localPort , long timeout ) { SocketFactory factory ; factory = new PlainSocketFactory ( address , port , localAddr , localPort , timeout ) ; factory = new PooledSocketFactory ( factory ) ; factory = new LazySocketFactory ( factory ) ; return factory ; } | Create socket factories for newly resolved addresses . Default implementation returns a LazySocketFactory wrapping a PooledSocketFactory wrapping a PlainSocketFactory . | 81 | 28 |
24,395 | public String encodeIntArray ( int [ ] input ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( bos ) ; int length = input . length ; dos . writeInt ( length ) ; for ( int i = 0 ; i < length ; i ++ ) { dos . writeInt ( input [ i ] ) ; } return new String ( Base64 . encodeBase64URLSafe ( bos . toByteArray ( ) ) ) ; } | Encode the given integer array into Base64 format . | 109 | 11 |
24,396 | public int [ ] decodeIntArray ( String input ) throws IOException { int [ ] result = null ; ByteArrayInputStream bis = new ByteArrayInputStream ( Base64 . decodeBase64 ( input ) ) ; DataInputStream dis = new DataInputStream ( bis ) ; int length = dis . readInt ( ) ; result = new int [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { result [ i ] = dis . readInt ( ) ; } return result ; } | Decode the given Base64 encoded value into an integer array . | 108 | 13 |
24,397 | public String decodeHexToString ( String str ) throws DecoderException { String result = null ; byte [ ] bytes = Hex . decodeHex ( str . toCharArray ( ) ) ; if ( bytes != null && bytes . length > 0 ) { result = new String ( bytes ) ; } return result ; } | Decode the given hexidecimal formatted value into a string representing the bytes of the decoded value . | 66 | 22 |
24,398 | public String getName ( ) { FeatureDescriptor fd = getFeatureDescriptor ( ) ; if ( fd == null ) { return null ; } return fd . getName ( ) ; } | Returns the feature name | 44 | 4 |
24,399 | public String getDescription ( ) { FeatureDescriptor fd = getFeatureDescriptor ( ) ; if ( fd == null ) { return "" ; } return getTeaToolsUtils ( ) . getDescription ( fd ) ; } | Returns the shortDescription or if the shortDescription is the same as the displayName . | 51 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.