idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
17,200
public static void copy ( final Path source , final Path dest ) throws IOException { if ( Files . exists ( source ) ) { Files . walkFileTree ( source , new SimpleFileVisitor < Path > ( ) { public FileVisitResult visitFile ( final Path file , final BasicFileAttributes attrs ) throws IOException { Files . copy ( file , resolve ( dest , relativize ( source , file ) ) ) ; return super . visitFile ( file , attrs ) ; } public FileVisitResult preVisitDirectory ( final Path dir , final BasicFileAttributes attrs ) throws IOException { Files . createDirectories ( resolve ( dest , relativize ( source , dir ) ) ) ; return super . preVisitDirectory ( dir , attrs ) ; } } ) ; } }
Copies a source to a destination works recursively on directories .
17,201
public static void delete ( final Path target ) throws IOException { if ( target != null && Files . exists ( target ) ) { Files . walkFileTree ( target , new SimpleFileVisitor < Path > ( ) { public FileVisitResult visitFile ( final Path file , final BasicFileAttributes attrs ) throws IOException { Files . delete ( file ) ; return super . visitFile ( file , attrs ) ; } public FileVisitResult postVisitDirectory ( final Path dir , final IOException exc ) throws IOException { Files . delete ( dir ) ; return super . postVisitDirectory ( dir , exc ) ; } } ) ; } }
Deletes a path including directories .
17,202
public ByteBuffer [ ] getBuffers ( int start , int len ) { if ( len == 0 ) { return ar0 ; } if ( len > capacity ) { throw new IllegalArgumentException ( "len=" + len + " > capacity=" + capacity ) ; } int s = start % capacity ; int e = ( start + len ) % capacity ; return getBuffersForSpan ( s , e ) ; }
Returns array of buffers that contains ringbuffers content in array of ByteBuffers ready for scattering read of gathering write
17,203
private boolean containsDate ( String [ ] strs , int tolerance ) { dfirst = - 1 ; dlast = - 1 ; int lastdw = - 999 ; int lastnum = - 999 ; int lastyear = - 999 ; for ( int i = 0 ; i < strs . length ; i ++ ) { if ( isMonthName ( strs [ i ] ) ) { lastdw = i ; if ( lastdw - lastnum <= tolerance ) return true ; } else if ( isYear ( strs [ i ] ) ) { lastyear = i ; if ( lastyear - lastnum <= tolerance ) return true ; } else if ( isNum ( strs [ i ] ) ) { lastnum = i ; if ( lastnum - lastdw <= tolerance ) return true ; } } return false ; }
Searches for sequences like num month or month num or num year in the string .
17,204
private boolean findDate ( String [ ] strs , int tolerance ) { dfirst = - 1 ; dlast = - 1 ; int curend = - 1 ; int intpos = - 1 ; for ( int i = 0 ; i < strs . length ; i ++ ) { if ( isMonthName ( strs [ i ] ) || isYear ( strs [ i ] ) ) intpos = i ; if ( intpos == i || isNum ( strs [ i ] ) ) { if ( isYear ( strs [ i ] ) ) intpos = i ; if ( curend == - 1 ) curend = i ; else { if ( i - curend <= tolerance ) curend = i ; else { if ( dlast - dfirst >= 1 && intpos >= dfirst && intpos <= dlast ) return true ; else { curend = i ; dfirst = i ; dlast = i ; } } } if ( dfirst == - 1 ) dfirst = curend ; dlast = curend ; } } return ( dlast - dfirst >= 1 ) ; }
Searches for sequences like num month or month num or num year in the string . If the date is found the dfirst and dlast properties are set to the indices of the first and last index of the corresponding words .
17,205
public void init ( Icon icon , String text ) { this . setText ( text ) ; this . setIcon ( icon ) ; this . setMargin ( JScreenConstants . NO_INSETS ) ; }
Creates new JCellButton . The icon and text are reversed because of a conflicting method in JButton .
17,206
public Component getTableCellRendererComponent ( JTable table , Object value , boolean isSelected , boolean hasFocus , int row , int column ) { if ( value == null ) this . setEnabled ( false ) ; else this . setEnabled ( true ) ; if ( hasFocus ) { this . setOpaque ( false ) ; this . setBorder ( JScreen . m_borderLine ) ; } else { this . setOpaque ( isSelected ) ; if ( isSelected ) this . setBackground ( table . getSelectionBackground ( ) ) ; this . setBorder ( null ) ; } return this ; }
Get the renderer for this location in the table . From the TableCellRenderer interface .
17,207
private byte [ ] alloc ( ) { position = 0 ; chunk ++ ; if ( chunk >= pool . size ( ) ) { byte [ ] bytes = new byte [ chunk == 0 ? initialSize : incrementalSize ] ; pool . add ( bytes ) ; } return chunk ( ) ; }
Activates the next chunk from the pool allocating it if necessary .
17,208
private byte getByte ( int index ) { if ( index < initialSize ) { return pool . get ( 0 ) [ index ] ; } index -= initialSize ; return pool . get ( index / incrementalSize + 1 ) [ index % incrementalSize ] ; }
Returns the byte at the specified index . No index validation is performed .
17,209
public void put ( byte [ ] bytes , int start , int end ) { byte [ ] buffer = chunk ( ) ; for ( int i = start ; i < end ; i ++ ) { if ( position == buffer . length ) { buffer = alloc ( ) ; } buffer [ position ++ ] = bytes [ i ] ; size ++ ; } }
Writes a range of bytes from the specified array .
17,210
public byte [ ] toArray ( ) { byte [ ] result = new byte [ size ] ; int pos = 0 ; for ( byte [ ] buffer : pool ) { for ( int i = 0 ; i < buffer . length && pos < size ; i ++ ) { result [ pos ++ ] = buffer [ i ] ; } } return result ; }
Returns the current contents of the buffer as a byte array .
17,211
public byte [ ] toArray ( int start , int end ) { checkIndex ( start ) ; checkIndex ( end ) ; byte [ ] result = new byte [ start > end ? 0 : end - start ] ; for ( int i = start ; i < end ; i ++ ) { result [ i ] = getByte ( i ) ; } return result ; }
Returns the range of bytes beginning at the start position and exclusive of the end position . If the start position is greater than or equal to the end position an empty array is returned .
17,212
public MDecimal getKelvin ( ) { MDecimal result = new MDecimal ( currentUnit . getConverterTo ( KELVIN ) . convert ( doubleValue ( ) ) ) ; logger . trace ( MMarker . GETTER , "Converting from {} to Fahrenheit : {}" , currentUnit , result ) ; return result ; }
Kelvin is the SI Unit
17,213
public int convertFieldToIndex ( ) { int index = - 1 ; FieldInfo field = this . getField ( ) ; if ( field != null ) { if ( ! field . isNull ( ) ) { boolean bFound = false ; Object bookmark = null ; try { if ( field instanceof ReferenceField ) if ( ( ( ReferenceField ) field ) . getReferenceRecord ( ) == m_record ) bookmark = ( ( ReferenceField ) field ) . getReference ( ) . getHandle ( DBConstants . BOOKMARK_HANDLE ) ; } catch ( DBException ex ) { bookmark = null ; } if ( bookmark == null ) if ( field instanceof IntegerField ) bookmark = field . getData ( ) ; Object bookmarkRecord = null ; try { bookmarkRecord = m_record . getTable ( ) . getHandle ( m_iHandleType ) ; } catch ( DBException ex ) { } if ( ( m_record . getEditMode ( ) == Constants . EDIT_IN_PROGRESS ) || ( m_record . getEditMode ( ) == Constants . EDIT_CURRENT ) ) if ( bookmarkRecord != null ) if ( bookmarkRecord . equals ( bookmark ) ) bFound = true ; if ( bFound == false ) if ( bookmark != null ) { index = m_gridTable . bookmarkToIndex ( bookmark , DBConstants . BOOKMARK_HANDLE ) ; if ( index != - 1 ) { if ( m_bIncludeBlankOption ) index ++ ; return index ; } try { bFound = ( m_record . getTable ( ) . setHandle ( bookmark , m_iHandleType ) != null ) ; } catch ( DBException e ) { bFound = false ; } } if ( bFound ) { index = m_gridTable . bookmarkToIndex ( bookmark , DBConstants . BOOKMARK_HANDLE ) ; if ( index != - 1 ) { try { m_gridTable . get ( index ) ; } catch ( DBException e ) { e . printStackTrace ( ) ; } } if ( m_bIncludeBlankOption ) index ++ ; if ( index != - 1 ) return index ; } } } this . moveToIndex ( - 1 ) ; if ( m_bIncludeBlankOption ) if ( field != null ) if ( field . isNull ( ) ) return 0 ; return - 1 ; }
Convert the current field value to an index .
17,214
public String convertIndexToDisStr ( int index ) { int iErrorCode = this . moveToIndex ( index ) ; if ( iErrorCode == DBConstants . NORMAL_RETURN ) { if ( displayFieldName != null ) return m_record . getField ( displayFieldName ) . getString ( ) ; else return m_record . getField ( m_iFieldSeq ) . getString ( ) ; } else return Constants . BLANK ; }
Convert this index value to a display string .
17,215
public void registerInitialProcesses ( ) { MessageProcessInfo recMessageProcessInfo = new MessageProcessInfo ( this ) ; try { this . registerProcessForMessage ( new BaseMessageFilter ( MessageConstants . TRX_SEND_QUEUE , MessageConstants . INTERNET_QUEUE , null , null ) , null , null ) ; recMessageProcessInfo . close ( ) ; while ( recMessageProcessInfo . hasNext ( ) ) { recMessageProcessInfo . next ( ) ; String strQueueName = recMessageProcessInfo . getQueueName ( true ) ; String strQueueType = recMessageProcessInfo . getQueueType ( true ) ; String strProcessClass = recMessageProcessInfo . getField ( MessageProcessInfo . PROCESSOR_CLASS ) . toString ( ) ; Map < String , Object > properties = ( ( PropertiesField ) recMessageProcessInfo . getField ( MessageProcessInfo . PROPERTIES ) ) . getProperties ( ) ; Record recMessageType = ( ( ReferenceField ) recMessageProcessInfo . getField ( MessageProcessInfo . MESSAGE_TYPE_ID ) ) . getReference ( ) ; if ( recMessageType != null ) { String strMessageType = recMessageType . getField ( MessageType . CODE ) . toString ( ) ; Record recMessageInfo = ( ( ReferenceField ) recMessageProcessInfo . getField ( MessageProcessInfo . MESSAGE_INFO_ID ) ) . getReference ( ) ; if ( recMessageInfo != null ) { Record recMessageInfoType = ( ( ReferenceField ) recMessageInfo . getField ( MessageInfo . MESSAGE_INFO_TYPE_ID ) ) . getReference ( ) ; if ( recMessageInfoType != null ) { String strMessageInfoType = recMessageInfoType . getField ( MessageInfoType . CODE ) . toString ( ) ; if ( MessageInfoType . REQUEST . equals ( strMessageInfoType ) ) if ( MessageType . MESSAGE_IN . equals ( strMessageType ) ) if ( ( strQueueName != null ) && ( strQueueName . length ( ) > 0 ) ) this . registerProcessForMessage ( new BaseMessageFilter ( strQueueName , strQueueType , null , null ) , strProcessClass , properties ) ; } } } } recMessageProcessInfo . close ( ) ; } catch ( DBException ex ) { ex . printStackTrace ( ) ; } finally { recMessageProcessInfo . free ( ) ; } }
RegisterInitialProcesses Method .
17,216
public void registerProcessForMessage ( BaseMessageFilter messageFilter , String strProcessClass , Map < String , Object > properties ) { new TrxMessageListener ( messageFilter , ( Application ) this . getTask ( ) . getApplication ( ) , strProcessClass , properties ) ; ( ( MessageInfoApplication ) this . getTask ( ) . getApplication ( ) ) . getThickMessageManager ( ) . addMessageFilter ( messageFilter ) ; if ( properties != null ) if ( properties . get ( MessageInfoApplication . AUTOSTART ) != null ) ( ( MessageInfoApplication ) this . getTask ( ) . getApplication ( ) ) . getThickMessageManager ( ) . sendMessage ( new MapMessage ( new BaseMessageHeader ( messageFilter . getQueueName ( ) , messageFilter . getQueueType ( ) , this , null ) , properties ) ) ; }
RegisterProcessForMessage Method .
17,217
public void setCountryCode ( final String code ) { if ( code . length ( ) != 2 ) { throw new IllegalArgumentException ( "Argument must be a two letter country code." ) ; } this . code = code . toUpperCase ( ) ; this . name = null ; }
Set the two letter country code .
17,218
public ListBuilder < T > add ( T ... items ) { list . addAll ( Arrays . asList ( items ) ) ; return this ; }
Adds items to the list .
17,219
public ListBuilder < T > addAll ( int index , Collection < ? extends T > items ) { list . addAll ( index , items ) ; return this ; }
Adds all items in the items Collection to the list .
17,220
public static String stateAbbr ( boolean allStates ) { String state = fetchString ( "address.state_abbr" ) ; if ( allStates == true ) { return state ; } else { while ( state . equalsIgnoreCase ( "FM" ) || state . equalsIgnoreCase ( "FL" ) || state . equalsIgnoreCase ( "GU" ) || state . equalsIgnoreCase ( "PW" ) || state . equalsIgnoreCase ( "PA" ) || state . equalsIgnoreCase ( "PR" ) || state . equalsIgnoreCase ( "AE" ) || state . equalsIgnoreCase ( "AA" ) || state . equalsIgnoreCase ( "AP" ) || state . equalsIgnoreCase ( "MP" ) || state . equalsIgnoreCase ( "VI" ) || state . equalsIgnoreCase ( "AS" ) || state . equalsIgnoreCase ( "MH" ) ) { state = stateAbbr ( true ) ; } } return state ; }
random 2 letter state
17,221
public boolean isChangeToNewID ( Record record ) { Record recClassInfo = this . getRecord ( ClassInfo . CLASS_INFO_FILE ) ; recClassInfo . setKeyArea ( ClassInfo . CLASS_NAME_KEY ) ; recClassInfo . getField ( ClassInfo . CLASS_NAME ) . moveFieldToThis ( record . getField ( ScreenIn . SCREEN_IN_PROG_NAME ) ) ; try { if ( ! recClassInfo . seek ( DBConstants . EQUALS ) ) return false ; } catch ( DBException e ) { e . printStackTrace ( ) ; } return ( recClassInfo . getField ( ClassInfo . CLASS_PROJECT_ID ) . getValue ( ) == 1 ) ; }
Change this to the new ID?
17,222
public ScaleLevel getLevelFor ( Font font , boolean horizontal , double xy ) { return getLevelFor ( font , DEFAULT_FONTRENDERCONTEXT , horizontal , xy ) ; }
Returns highest level where drawn labels don t overlap using identity transformer and FontRenderContext with identity AffineTransform no anti - aliasing and fractional metrics
17,223
public List < String > getLabels ( Locale locale , ScaleLevel level ) { return level . stream ( min , max ) . mapToObj ( ( d ) -> level . label ( locale , d ) ) . collect ( Collectors . toList ( ) ) ; }
Returns labels for level
17,224
public ScaleLevel level ( int minMarkers , int maxMarkers ) { Iterator < ScaleLevel > iterator = scale . iterator ( min , max ) ; ScaleLevel level = iterator . next ( ) ; ScaleLevel prev = null ; while ( iterator . hasNext ( ) && minMarkers > level . count ( min , max ) ) { prev = level ; level = iterator . next ( ) ; } if ( maxMarkers < level . count ( min , max ) ) { return prev ; } else { return level ; } }
Returns minimum level where number of markers is not less that minMarkers and less than maxMarkers . If both cannot be met maxMarkers is stronger .
17,225
public String getHtmlControl ( ) { StringWriter sw = new StringWriter ( ) ; PrintWriter rw = new PrintWriter ( sw ) ; this . getScreenField ( ) . printData ( rw , HtmlConstants . HTML_DISPLAY ) ; String string = sw . toString ( ) ; return string ; }
Get this report s output as an HTML string .
17,226
public void windowClosing ( WindowEvent e ) { if ( m_dialog . getContentPane ( ) . getComponentCount ( ) > 0 ) if ( m_dialog . getContentPane ( ) . getComponent ( 0 ) instanceof BaseApplet ) ( ( BaseApplet ) m_dialog . getContentPane ( ) . getComponent ( 0 ) ) . free ( ) ; m_dialog . dispose ( ) ; }
The window is closing free the sub - BaseApplet .
17,227
public JSONArray getJSONMeasures ( String content ) { JSONArray ja = new JSONArray ( ) ; for ( Entry < String , String > measure : measureRegexps . entrySet ( ) ) { Pattern r = Pattern . compile ( measure . getValue ( ) ) ; Matcher m = r . matcher ( content ) ; if ( m . find ( ) ) { JSONObject jsonMeasure = new JSONObject ( ) ; jsonMeasure . put ( measure . getKey ( ) , m . group ( 1 ) ) ; ja . add ( jsonMeasure ) ; } } return ja ; }
Obtains a JSONArray with the measures extracted from a string passed by argument .
17,228
public HashMap < String , Double > getArrayMeasures ( JSONObject jsonContent ) { HashMap < String , Double > i = new HashMap < String , Double > ( ) ; return i ; }
Obtains a HashMap with the measures extracted from a JSONObject representing the sensor data .
17,229
public void fillMeasures ( String measure , JSONObject jsonContent , Pattern pattern , HashMap < String , Double > i ) { String tem = ( String ) jsonContent . get ( measure ) ; if ( tem != null ) { Matcher tM = pattern . matcher ( tem ) ; if ( tM . find ( ) && ! tM . group ( 1 ) . isEmpty ( ) ) { try { i . put ( measure , Double . valueOf ( tM . group ( 1 ) ) ) ; } catch ( NumberFormatException e ) { e . printStackTrace ( ) ; } } } }
Extracts a pattern from a measure value located in a JSONObject and stores it in a HashMap whether finds it .
17,230
public static < T > boolean isInteger ( Class < T > field ) { return Integer . class . getSimpleName ( ) . equalsIgnoreCase ( field . getSimpleName ( ) ) ; }
Test if a field is Integer .
17,231
public static < T > boolean isLong ( Class < T > field ) { return Long . class . getSimpleName ( ) . equalsIgnoreCase ( field . getSimpleName ( ) ) ; }
Test if a field is Long .
17,232
public boolean isCacheValue ( Object objKey ) { if ( m_hmCache == null ) return false ; if ( objKey == null ) return false ; Class < ? > classKey = this . getField ( ) . getDataClass ( ) ; objKey = this . convertKey ( objKey , classKey ) ; return m_hmCache . containsKey ( objKey ) ; }
Is this key cached?
17,233
public ImageIcon getCacheValue ( Object objKey ) { if ( m_hmCache == null ) return null ; if ( objKey == null ) return null ; Class < ? > classKey = this . getField ( ) . getDataClass ( ) ; objKey = this . convertKey ( objKey , classKey ) ; return ( ImageIcon ) m_hmCache . get ( objKey ) ; }
Get the cache value .
17,234
public void cacheValue ( Object objKey , Object objValue ) { if ( objKey == null ) return ; Class < ? > classKey = this . getField ( ) . getDataClass ( ) ; objKey = this . convertKey ( objKey , classKey ) ; if ( m_hmCache == null ) m_hmCache = new HashMap < Object , Object > ( ) ; m_hmCache . put ( objKey , objValue ) ; }
Add this key and value to the cache .
17,235
public static boolean isAbout ( double expected , double value , double tolerance ) { double delta = expected * tolerance / 100.0 ; return value > expected - delta && value < expected + delta ; }
Returns true if value differs only tolerance percent .
17,236
public int fieldChanged ( boolean bDisplayOption , int moveMode ) { int iScreenNo = ( int ) ( ( NumberField ) m_owner ) . getValue ( ) ; if ( ( iScreenNo == - 1 ) || ( iScreenNo == m_iCurrentScreenNo ) ) return DBConstants . NORMAL_RETURN ; ScreenLocation screenLocation = null ; this . setCurrentSubScreen ( null ) ; BaseAppletReference applet = null ; if ( m_screenParent . getTask ( ) instanceof BaseAppletReference ) applet = ( BaseAppletReference ) m_screenParent . getTask ( ) ; Object oldCursor = null ; if ( applet != null ) oldCursor = applet . setStatus ( DBConstants . WAIT , applet , null ) ; ScreenField sField = m_screenParent . getSField ( m_iScreenSeq ) ; if ( ( sField != null ) && ( sField instanceof BaseScreen ) ) { screenLocation = sField . getScreenLocation ( ) ; m_screenParent = sField . getParentScreen ( ) ; sField . free ( ) ; sField = null ; if ( m_screenParent == null ) if ( this . getOwner ( ) . getComponent ( 0 ) instanceof ScreenField ) m_screenParent = ( ( ScreenField ) this . getOwner ( ) . getComponent ( 0 ) ) . getParentScreen ( ) ; } if ( screenLocation == null ) screenLocation = m_screenParent . getNextLocation ( ScreenConstants . FLUSH_LEFT , ScreenConstants . FILL_REMAINDER ) ; sField = this . getSubScreen ( m_screenParent , screenLocation , null , iScreenNo ) ; if ( applet != null ) applet . setStatus ( 0 , applet , oldCursor ) ; if ( sField == null ) m_iCurrentScreenNo = - 1 ; else m_iCurrentScreenNo = iScreenNo ; return DBConstants . NORMAL_RETURN ; }
The Field has Changed . Get the value of this listener s field and setup the new sub - screen .
17,237
public BasePanel getSubScreen ( BasePanel parentScreen , ScreenLocation screenLocation , Map < String , Object > properties , int screenNo ) { return null ; }
Build this sub - screen .
17,238
public void setCurrentSubScreen ( BasePanel subScreen ) { m_screenParent = null ; m_iScreenSeq = - 1 ; if ( subScreen != null ) m_screenParent = subScreen . getParentScreen ( ) ; if ( m_screenParent == null ) if ( this . getOwner ( ) != null ) if ( this . getOwner ( ) . getRecord ( ) != null ) m_screenParent = ( BaseScreen ) this . getOwner ( ) . getRecord ( ) . getRecordOwner ( ) ; if ( m_screenParent == null ) if ( this . getOwner ( ) != null ) if ( this . getOwner ( ) . getComponent ( 0 ) instanceof ScreenField ) m_screenParent = ( ( ScreenField ) this . getOwner ( ) . getComponent ( 0 ) ) . getParentScreen ( ) ; if ( m_screenParent == null ) return ; int iBestGuess = - 1 ; for ( m_iScreenSeq = 0 ; m_iScreenSeq < m_screenParent . getSFieldCount ( ) ; m_iScreenSeq ++ ) { ScreenField sField = m_screenParent . getSField ( m_iScreenSeq ) ; if ( sField == subScreen ) return ; if ( sField instanceof BaseScreen ) iBestGuess = m_iScreenSeq ; } m_iScreenSeq = iBestGuess ; }
Set up m_iScreenSeq so I can find this sub - screen .
17,239
public void init ( final Class < ? > [ ] classes , final GlobalHeader globalHeader , final String baseURI ) { if ( ! this . initialized . compareAndSet ( false , true ) ) { throw new RestDocException ( "Generator already initialized" ) ; } this . logger . info ( "Starting generation of RestDoc" ) ; this . logger . info ( "Searching for RestDoc API classes" ) ; if ( globalHeader != null ) { if ( globalHeader . getRequestHeader ( ) != null ) { this . requestHeaderMap . putAll ( globalHeader . getRequestHeader ( ) ) ; } if ( globalHeader . getResponseHeader ( ) != null ) { this . responseHeaderMap . putAll ( globalHeader . getResponseHeader ( ) ) ; } if ( ( globalHeader . getAdditionalFields ( ) != null ) && ! globalHeader . getAdditionalFields ( ) . isEmpty ( ) ) { this . globalAdditional . putAll ( globalHeader . getAdditionalFields ( ) ) ; } } for ( final Class < ? > apiClass : classes ) { boolean scanNeeded = true ; if ( Arrays . asList ( apiClass . getInterfaces ( ) ) . contains ( IProvideRestDoc . class ) ) { try { this . logger . info ( "Class {} provides predefined RestDoc" , apiClass . getCanonicalName ( ) ) ; final IProvideRestDoc apiObject = ( IProvideRestDoc ) apiClass . newInstance ( ) ; final RestResource [ ] restDocResources = apiObject . getRestDocResources ( ) ; for ( final RestResource restResource : restDocResources ) { this . resources . put ( restResource . getPath ( ) , restResource ) ; } this . schemaMap . putAll ( apiObject . getRestDocSchemas ( ) ) ; scanNeeded = false ; } catch ( final Exception e ) { } } if ( scanNeeded ) { this . addResourcesOfClass ( apiClass , baseURI ) ; } } }
initialize the RestDoc Generator
17,240
public SelKey register ( ChannelSelector sel , Op ops , Object att ) { if ( selector != null ) { throw new IllegalStateException ( "already registered with " + selector ) ; } if ( validOp != ops ) { throw new IllegalArgumentException ( "expected " + validOp + " got " + ops ) ; } key = sel . register ( this , ops , att ) ; selector = sel ; return key ; }
Registers channel for selection .
17,241
public void displayError ( DBException ex ) { if ( ( ex instanceof DatabaseException ) && ( ex . getErrorCode ( ) == Constants . DUPLICATE_KEY ) ) this . displayError ( "Account already exists, sign-in using this user name" , DBConstants . WARNING_MESSAGE ) ; else super . displayError ( ex ) ; }
DisplayError Method .
17,242
protected void after ( ) { super . after ( ) ; if ( adminSession != null ) { LOG . info ( "Logging off {}" , adminSession . getUserID ( ) ) ; adminSession . logout ( ) ; adminSession = null ; } if ( anonSession != null ) { LOG . info ( "Logging off {}" , anonSession . getUserID ( ) ) ; anonSession . logout ( ) ; anonSession = null ; } for ( final Session session : userSessions . values ( ) ) { LOG . info ( "Logging off {}" , session . getUserID ( ) ) ; session . logout ( ) ; } userSessions . clear ( ) ; LOG . info ( "Closed all sessions" ) ; }
Closes all sessions
17,243
public Session login ( ) throws RepositoryException { assertStateAfterOrEqual ( State . CREATED ) ; final Session session ; if ( username != null && password != null ) { session = getRepository ( ) . login ( new SimpleCredentials ( username , password . toCharArray ( ) ) ) ; userSessions . put ( username , session ) ; } else if ( anonSession == null ) { anonSession = getRepository ( ) . login ( ) ; session = anonSession ; } else { session = anonSession ; } return session ; }
Logs into the repository . If a username and password has been specified is is used for the login otherwise an anonymous login is done .
17,244
public Session login ( final String username , final String password ) throws RepositoryException { assertStateAfterOrEqual ( State . CREATED ) ; if ( ! userSessions . containsKey ( username ) ) { userSessions . put ( username , getRepository ( ) . login ( new SimpleCredentials ( username , password . toCharArray ( ) ) ) ) ; } return userSessions . get ( username ) ; }
Creates a login for the given username and password
17,245
public static IntArray getInstance ( byte [ ] buffer , int offset , int length ) { return getInstance ( buffer , offset , length , 8 , ByteOrder . BIG_ENDIAN ) ; }
Creates IntArray backed by byte array
17,246
public static IntArray getInstance ( short [ ] buffer , int offset , int length ) { return getInstance ( ShortBuffer . wrap ( buffer , offset , length ) ) ; }
Creates IntArray backed by short array
17,247
public static IntArray getInstance ( int [ ] buffer , int offset , int length ) { return getInstance ( IntBuffer . wrap ( buffer , offset , length ) ) ; }
Creates IntArray backed by int array
17,248
public static IntArray getInstance ( int size , int bitCount , ByteOrder order ) { switch ( bitCount ) { case 8 : return getInstance ( new byte [ size ] , bitCount , order ) ; case 16 : return getInstance ( new byte [ 2 * size ] , bitCount , order ) ; case 32 : return new InArray ( size ) ; default : throw new UnsupportedOperationException ( bitCount + " not supported" ) ; } }
Creates IntArray of given length bitCount and byte - order
17,249
public void copy ( IntArray to ) { if ( length ( ) != to . length ( ) ) { throw new IllegalArgumentException ( "array not same size" ) ; } if ( buffer . hasArray ( ) && to . buffer . hasArray ( ) && buffer . array ( ) . getClass ( ) . getComponentType ( ) == to . buffer . array ( ) . getClass ( ) . getComponentType ( ) ) { System . arraycopy ( to . buffer . array ( ) , 0 , buffer . array ( ) , 0 , length ( ) ) ; } else { int len = length ( ) ; for ( int ii = 0 ; ii < len ; ii ++ ) { put ( ii , to . get ( ii ) ) ; } } }
Copies given IntArrays values to this . Throws IllegalArgumentException if lengths are not same .
17,250
public void forEach ( IntBiConsumer consumer ) { int len = length ( ) ; for ( int ii = 0 ; ii < len ; ii ++ ) { consumer . accept ( ii , get ( ii ) ) ; } }
Calls consumer for each index and value
17,251
public List < String > getClasses ( ) { String classAttr = getAttribute ( "class" ) ; return Stream . of ( ( classAttr == null ? "" : classAttr ) . trim ( ) . split ( "\\s+" ) ) . distinct ( ) . sorted ( ) . collect ( Collectors . toList ( ) ) ; }
Returns the class names present on element . The result is a unique set and is in alphabetical order .
17,252
public static Pair < String , String > getAndValidateKeyValuePair ( final String keyValueString ) throws InvalidKeyValueException { String tempInput [ ] = StringUtilities . split ( keyValueString , '=' , 2 ) ; tempInput = CollectionUtilities . trimStringArray ( tempInput ) ; if ( tempInput . length >= 2 ) { final String value = tempInput [ 1 ] ; return new Pair < String , String > ( tempInput [ 0 ] , replaceEscapeChars ( cleanXMLCharacterReferences ( value ) ) ) ; } else if ( tempInput . length >= 1 && keyValueString . contains ( "=" ) ) { return new Pair < String , String > ( tempInput [ 0 ] , "" ) ; } else { throw new InvalidKeyValueException ( ) ; } }
Validates a KeyValue pair for a content specification and then returns the processed key and value ..
17,253
public static PropertyTagInTopicWrapper cloneTopicProperty ( final TopicWrapper topic , final PropertyTagProvider propertyTagProvider , final PropertyTagInTopicWrapper originalProperty ) { final PropertyTagWrapper propertyTag = propertyTagProvider . getPropertyTag ( originalProperty . getId ( ) ) ; final PropertyTagInTopicWrapper newPropertyTag = propertyTagProvider . newPropertyTagInTopic ( propertyTag , topic ) ; newPropertyTag . setName ( originalProperty . getName ( ) ) ; newPropertyTag . setValue ( originalProperty . getValue ( ) ) ; return newPropertyTag ; }
Clones a Topic Property Tag .
17,254
public static TopicSourceURLWrapper cloneTopicSourceUrl ( final TopicSourceURLProvider topicSourceUrlProvider , final TopicSourceURLWrapper originalSourceUrl , final TopicWrapper parent ) { final TopicSourceURLWrapper sourceUrl = topicSourceUrlProvider . newTopicSourceURL ( parent ) ; sourceUrl . setTitle ( originalSourceUrl . getTitle ( ) ) ; sourceUrl . setDescription ( originalSourceUrl . getDescription ( ) ) ; sourceUrl . setUrl ( originalSourceUrl . getUrl ( ) ) ; return sourceUrl ; }
Clones a Topic Source URL
17,255
protected SessionFactory createSessionFactory ( ) { StandardServiceRegistryBuilder b = new StandardServiceRegistryBuilder ( ) ; ServiceRegistry registry = b . configure ( ) . build ( ) ; return new MetadataSources ( registry ) . buildMetadata ( ) . buildSessionFactory ( ) ; }
Create a session factory given the current configuration method .
17,256
public void contextInitialized ( final ServletContextEvent servletContextEvent ) { logger . info ( "Rebuilding Search Index..." ) ; SessionFactory factory = createSessionFactory ( ) ; Session session = factory . openSession ( ) ; FullTextSession fullTextSession = Search . getFullTextSession ( session ) ; try { fullTextSession . createIndexer ( ) . startAndWait ( ) ; } catch ( InterruptedException e ) { logger . warn ( "Search reindex interrupted. Good luck!" ) ; logger . trace ( "Error:" , e ) ; } finally { session . close ( ) ; factory . close ( ) ; } }
Rebuild the search index during context initialization .
17,257
public static String getImage ( Priority priority ) { String image = getLabel ( "icon" , priority ) ; return image == null ? null : IconUtil . getIconPath ( image ) ; }
Returns the url of the graphical representation of the priority .
17,258
private static String getLabel ( String name , Priority priority ) { return priority == null ? null : Labels . getLabel ( "vistanotification.priority." + name + "." + priority . name ( ) ) ; }
Returns the label property for the specified attribute name and priority .
17,259
public void onReceive ( Object object ) { if ( ! closed && object != null ) { synchronized ( queue ) { queue . addLast ( object ) ; if ( limit > 0 && queue . size ( ) > limit && ! queue . isEmpty ( ) ) { queue . removeFirst ( ) ; } } } }
Receives an object from a channel .
17,260
public String getString ( String string ) { if ( this . getRecord ( ) != null ) if ( this . getRecord ( ) . getTask ( ) != null ) string = this . getRecord ( ) . getTask ( ) . getString ( string ) ; return string ; }
Look up this string in the resource table . This is a convience method - calls getString in the task .
17,261
public void add ( Matcher matcher , T attachment ) { add ( matcher ) ; map . add ( matcher , attachment ) ; }
Add matcher with attachment . If matcher exist only attachment is stored .
17,262
public Status match ( int cc ) { int highest = - 1 ; Iterator < Matcher > iterator = active . iterator ( ) ; while ( iterator . hasNext ( ) ) { Matcher matcher = iterator . next ( ) ; Status s = matcher . match ( cc ) ; highest = Math . max ( highest , s . ordinal ( ) ) ; switch ( s ) { case Match : lastMatched = matcher ; clear ( ) ; return s ; case WillMatch : lastMatched = matcher ; return s ; case Error : iterator . remove ( ) ; break ; } } if ( active . isEmpty ( ) ) { clear ( ) ; return Status . Error ; } return Status . values ( ) [ highest ] ; }
If one matches returns Match . If all return Error returns error . Otherwise returns Ok .
17,263
public void add ( double x , double y , int k ) { sx += x * k ; sy += y * k ; sxy += x * y * k ; sx2 += x * x * k ; n += k ; if ( n < 1 ) { throw new IllegalArgumentException ( "negative count" ) ; } }
Adds a point k times . k can be negative .
17,264
public double getY ( double x ) { double slope = getSlope ( ) ; double a = getYIntercept ( slope ) ; if ( ! Double . isInfinite ( slope ) ) { return slope * x + a ; } else { if ( x == a ) { return Double . POSITIVE_INFINITY ; } else { return Double . NaN ; } } }
Returns y - value for x
17,265
public AbstractLine getLine ( ) { double slope = getSlope ( ) ; double yIntercept = getYIntercept ( slope ) ; return new AbstractLine ( slope , 0 , yIntercept ) ; }
Returns best - fit - line
17,266
public void sendNotification ( final String requestHost , final String topic ) { assert validTopics . isEmpty ( ) || validTopics . contains ( topic ) : "That topic is not supported by this hub. " + topic ; LOG . debug ( "Sending notification for {}" , topic ) ; try { final List < ? extends Subscriber > subscribers = dao . subscribersForTopic ( topic ) ; if ( subscribers . isEmpty ( ) ) { LOG . debug ( "No subscribers to notify for {}" , topic ) ; return ; } final List < ? extends SubscriptionSummary > summaries = dao . summariesForTopic ( topic ) ; int total = 0 ; final StringBuilder hosts = new StringBuilder ( ) ; for ( final SubscriptionSummary s : summaries ) { if ( s . getSubscribers ( ) > 0 ) { total += s . getSubscribers ( ) ; hosts . append ( " (" ) . append ( s . getHost ( ) ) . append ( "; " ) . append ( s . getSubscribers ( ) ) . append ( " subscribers)" ) ; } } final StringBuilder userAgent = new StringBuilder ( "ROME-Certiorem (+http://" ) . append ( requestHost ) . append ( "; " ) . append ( total ) . append ( " subscribers)" ) . append ( hosts ) ; final SyndFeed feed = fetcher . retrieveFeed ( userAgent . toString ( ) , new URL ( topic ) ) ; LOG . debug ( "Got feed for {} Sending to {} subscribers." , topic , subscribers . size ( ) ) ; notifier . notifySubscribers ( subscribers , feed , new SubscriptionSummaryCallback ( ) { public void onSummaryInfo ( final SubscriptionSummary summary ) { dao . handleSummary ( topic , summary ) ; } } ) ; } catch ( final Exception ex ) { LOG . debug ( "Exception getting " + topic , ex ) ; throw new HttpStatusCodeException ( 500 , ex . getMessage ( ) , ex ) ; } }
Sends a notification to the subscribers
17,267
public static byte [ ] toByteArray ( final File tmpFile ) throws IOException { byte [ ] data = null ; if ( tmpFile . exists ( ) && ! tmpFile . isDirectory ( ) ) { try ( BufferedInputStream bis = new BufferedInputStream ( new FileInputStream ( tmpFile ) ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( FileConst . KILOBYTE ) ; ) { StreamExtensions . writeInputStreamToOutputStream ( bis , bos ) ; data = bos . toByteArray ( ) ; } } return data ; }
Get a byte array from the given file .
17,268
private static void trustAllHosts ( ) { TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public java . security . cert . X509Certificate [ ] getAcceptedIssuers ( ) { return new java . security . cert . X509Certificate [ ] { } ; } public void checkClientTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } public void checkServerTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } } } ; try { SSLContext sc = SSLContext . getInstance ( "TLS" ) ; sc . init ( null , trustAllCerts , new java . security . SecureRandom ( ) ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( sc . getSocketFactory ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Trust every server - dont check for any certificate
17,269
public static void initGlobals ( ) { if ( gDateFormat == null ) { gCalendar = Calendar . getInstance ( ) ; gDateFormat = DateFormat . getDateInstance ( DateFormat . MEDIUM ) ; gTimeFormat = DateFormat . getTimeInstance ( DateFormat . SHORT ) ; gLongTimeFormat = DateFormat . getTimeInstance ( DateFormat . MEDIUM ) ; gDateTimeFormat = DateFormat . getDateTimeInstance ( DateFormat . MEDIUM , DateFormat . SHORT ) ; gLongDateTimeFormat = DateFormat . getDateTimeInstance ( DateFormat . MEDIUM , DateFormat . MEDIUM ) ; gDateShortFormat = DateFormat . getDateInstance ( DateFormat . SHORT ) ; gDateShortTimeFormat = DateFormat . getDateTimeInstance ( DateFormat . SHORT , DateFormat . SHORT ) ; gGMTDateTimeFormat = new SimpleDateFormat ( "EEE MMM dd HH:mm:ss zzz yyyy" , Locale . US ) ; gDateSqlFormat = gDateShortFormat ; gTimeSqlFormat = gTimeFormat ; gDateTimeSqlFormat = gDateShortTimeFormat ; gIntegerFormat = NumberFormat . getInstance ( ) ; gIntegerFormat . setParseIntegerOnly ( true ) ; gCurrencyFormat = NumberFormat . getCurrencyInstance ( ) ; gNumberFormat = NumberFormat . getInstance ( ) ; gNumberFormat . setParseIntegerOnly ( false ) ; gNumberFormat . setMinimumFractionDigits ( 2 ) ; gNumberFormat . setMaximumFractionDigits ( 2 ) ; if ( gNumberFormat instanceof DecimalFormat ) { gchDot = ( ( DecimalFormat ) gNumberFormat ) . getDecimalFormatSymbols ( ) . getDecimalSeparator ( ) ; gchMinus = ( ( DecimalFormat ) gNumberFormat ) . getDecimalFormatSymbols ( ) . getMinusSign ( ) ; } gPercentFormat = NumberFormat . getPercentInstance ( ) ; } }
Initialize the global text format classes .
17,270
public static String stripNonNumber ( String string ) { if ( string == null ) return null ; for ( int i = 0 ; i < string . length ( ) ; i ++ ) { char ch = string . charAt ( i ) ; if ( ! ( Character . isDigit ( ch ) ) ) if ( ch != gchDot ) if ( ch != gchMinus ) { string = string . substring ( 0 , i ) + string . substring ( i + 1 ) ; i -- ; } } return string ; }
Utility to strip all the non - numeric characters from this string .
17,271
public static Short stringToShort ( String strString ) throws Exception { Number objData ; initGlobals ( ) ; if ( ( strString == null ) || ( strString . equals ( Constant . BLANK ) ) ) return null ; strString = DataConverters . stripNonNumber ( strString ) ; try { synchronized ( gIntegerFormat ) { objData = gIntegerFormat . parse ( strString ) ; } if ( ! ( objData instanceof Short ) ) { if ( objData instanceof Number ) objData = new Short ( objData . shortValue ( ) ) ; else objData = null ; } } catch ( ParseException ex ) { objData = null ; } if ( objData == null ) { try { objData = new Short ( strString ) ; } catch ( NumberFormatException ex ) { throw ex ; } } return ( Short ) objData ; }
Convert this string to a Short .
17,272
public static Integer stringToInteger ( String strString ) throws Exception { Number objData ; initGlobals ( ) ; if ( ( strString == null ) || ( strString . equals ( Constant . BLANK ) ) ) return null ; strString = DataConverters . stripNonNumber ( strString ) ; try { synchronized ( gIntegerFormat ) { objData = gIntegerFormat . parse ( strString ) ; } if ( ! ( objData instanceof Integer ) ) { if ( objData instanceof Number ) objData = new Integer ( objData . intValue ( ) ) ; else objData = null ; } } catch ( ParseException ex ) { objData = null ; } if ( objData == null ) if ( strString != null ) if ( strString . length ( ) > 0 ) { try { objData = new Integer ( strString ) ; } catch ( NumberFormatException ex ) { throw ex ; } } return ( Integer ) objData ; }
Convert this string to a Integer .
17,273
public static Float stringToFloat ( String strString , int ibScale ) throws Exception { Number objData ; initGlobals ( ) ; if ( ( strString == null ) || ( strString . equals ( Constant . BLANK ) ) ) return null ; strString = DataConverters . stripNonNumber ( strString ) ; try { synchronized ( gNumberFormat ) { objData = gNumberFormat . parse ( strString ) ; } if ( ! ( objData instanceof Float ) ) { if ( objData instanceof Number ) objData = new Float ( objData . floatValue ( ) ) ; else objData = null ; } } catch ( ParseException ex ) { objData = null ; } if ( objData == null ) { try { objData = new Float ( strString ) ; } catch ( NumberFormatException ex ) { throw ex ; } } if ( ibScale != - 1 ) objData = new Float ( Math . floor ( ( ( Float ) objData ) . floatValue ( ) * Math . pow ( 10 , ibScale ) + 0.5 ) / Math . pow ( 10 , ibScale ) ) ; return ( Float ) objData ; }
Convert this string to a Float .
17,274
public static Double stringToDouble ( String strString , int ibScale ) throws Exception { Number objData ; initGlobals ( ) ; if ( ( strString == null ) || ( strString . equals ( Constant . BLANK ) ) ) return null ; strString = DataConverters . stripNonNumber ( strString ) ; try { synchronized ( gNumberFormat ) { objData = gNumberFormat . parse ( strString ) ; } if ( ! ( objData instanceof Double ) ) { if ( objData instanceof Number ) objData = new Double ( objData . doubleValue ( ) ) ; else objData = null ; } } catch ( ParseException ex ) { objData = null ; } if ( objData == null ) { try { objData = new Double ( strString ) ; } catch ( NumberFormatException ex ) { throw ex ; } } if ( ibScale != - 1 ) objData = new Double ( Math . floor ( ( ( Double ) objData ) . doubleValue ( ) * Math . pow ( 10 , ibScale ) + 0.5 ) / Math . pow ( 10 , ibScale ) ) ; return ( Double ) objData ; }
Convert this string to a Double .
17,275
public static String getAbsolutePath ( final File file , final boolean removeLastChar ) { String absolutePath = file . getAbsolutePath ( ) ; if ( removeLastChar ) { absolutePath = absolutePath . substring ( 0 , absolutePath . length ( ) - 1 ) ; } return absolutePath ; }
Gets the absolute path .
17,276
public static File getProjectDirectory ( final File currentDir ) { final String projectPath = PathFinder . getAbsolutePath ( currentDir , true ) ; final File projectFile = new File ( projectPath ) ; return projectFile ; }
Gets the project directory .
17,277
@ SuppressWarnings ( "rawtypes" ) public < T > T asObject ( String string , Class < T > valueType ) throws IllegalArgumentException { if ( string . isEmpty ( ) ) { return null ; } if ( Types . isKindOf ( valueType , OrdinalEnum . class ) ) { return valueType . getEnumConstants ( ) [ Integer . parseInt ( string ) ] ; } return ( T ) Enum . valueOf ( ( Class ) valueType , string ) ; }
Create enumeration constant for given string and enumeration type .
17,278
public String asString ( Object object ) { Enum < ? > e = ( Enum < ? > ) object ; if ( object instanceof OrdinalEnum ) { return Integer . toString ( e . ordinal ( ) ) ; } return e . name ( ) ; }
Get enumeration constant name .
17,279
public Message receiveMessage ( ) { Message message = null ; try { message = m_receiveQueue . receiveRemoteMessage ( ) ; } catch ( RemoteException ex ) { ex . printStackTrace ( ) ; return null ; } if ( message instanceof BaseMessage ) ( ( BaseMessage ) message ) . setProcessedByServer ( true ) ; return message ; }
Block until a message is received . Hangs on the remote receive message call .
17,280
public boolean removeMessageFilter ( MessageFilter messageFilter , boolean bFreeFilter ) { boolean bSuccess = false ; try { if ( ( ( BaseMessageFilter ) messageFilter ) . getRemoteFilterID ( ) == null ) bSuccess = true ; else bSuccess = m_receiveQueue . removeRemoteMessageFilter ( ( BaseMessageFilter ) messageFilter , bFreeFilter ) ; } catch ( RemoteException ex ) { ex . printStackTrace ( ) ; } if ( ! bSuccess ) Util . getLogger ( ) . warning ( "Remote listener not removed" ) ; return super . removeMessageFilter ( messageFilter , bFreeFilter ) ; }
Remove this message filter from this queue . Also remove the remote message filter .
17,281
public boolean isSendRemoteMessage ( BaseMessage message ) { Iterator < BaseMessageFilter > iterator = this . getMessageFilterList ( ) . getFilterList ( null ) ; while ( iterator . hasNext ( ) ) { BaseMessageFilter filter = iterator . next ( ) ; if ( ! filter . isRemoteFilter ( ) ) if ( filter . isSendRemoteMessage ( message ) == false ) return false ; } return true ; }
Do I send this message to the remote server? Remember to check for the filter match .
17,282
public LockTable getLockTable ( String strDatabaseName , String strRecordName ) { String strKey = strDatabaseName + ':' + strRecordName ; LockTable lockTable = ( LockTable ) m_htLockTables . get ( strKey ) ; if ( lockTable == null ) { synchronized ( m_htLockTables ) { if ( ( lockTable = ( LockTable ) m_htLockTables . get ( strKey ) ) == null ) m_htLockTables . put ( strKey , lockTable = new LockTable ( ) ) ; } m_hsMyLockTables . add ( lockTable ) ; } return lockTable ; }
Get the lock table for this record .
17,283
public static String getName ( final int parts ) { final StringBuilder buff = new StringBuilder ( ) ; for ( int i = 0 ; i < parts ; i ++ ) { if ( buff . length ( ) != 0 ) { buff . append ( '-' ) ; } buff . append ( NATOALPHABET [ ( int ) ( Math . random ( ) * NATOALPHABET . length ) ] ) ; } return buff . toString ( ) ; }
Creates a random name .
17,284
public void setRegistry ( BridgeHeadTypeRegistry registry ) { this . registry . set ( registry ) ; for ( FactoryAccessor < ? > accessor : accessors ) { registry . injectInto ( accessor ) ; } }
Sets the registry that maps types to bridge factories .
17,285
public static List < String > formatKommaSeperatedFileToList ( final File input , final String encoding ) throws IOException { final List < String > output = new ArrayList < > ( ) ; try ( BufferedReader reader = ( BufferedReader ) StreamExtensions . getReader ( input , encoding , false ) ) { String line = null ; do { line = reader . readLine ( ) ; if ( line == null ) { break ; } final String [ ] splittedData = line . split ( "," ) ; for ( final String element : splittedData ) { output . add ( element . trim ( ) ) ; } } while ( true ) ; } return output ; }
Reads every line from the File splits the data through a comma and puts them to the List .
17,286
private static String formatListToString ( final List < String > list ) { int lineLength = 0 ; final StringBuffer sb = new StringBuffer ( ) ; for ( final String str : list ) { final int length = str . length ( ) ; lineLength = length + lineLength ; sb . append ( str ) ; sb . append ( ", " ) ; if ( 100 < lineLength ) { sb . append ( "\n" ) ; lineLength = 0 ; } } return sb . toString ( ) . trim ( ) ; }
Formats the List that contains String - object to a csv - file wich is plus - minus 100 characters in every line .
17,287
public static void formatToCSV ( final File input , final File output , final String encoding ) throws IOException { final List < String > list = readLinesInList ( input , "UTF-8" ) ; final String sb = formatListToString ( list ) ; WriteFileExtensions . writeStringToFile ( output , sb , encoding ) ; }
Formats a file that has in every line one input - data into a csv - file .
17,288
public static Properties readFilelistToProperties ( final File input ) throws IOException { final List < String > list = readLinesInList ( input , null ) ; final Properties prop = new Properties ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { final String element = list . get ( i ) ; prop . put ( i + "" , element ) ; } return prop ; }
Read filelist to properties .
17,289
public static List < String > readFileToList ( final File file , final String encoding ) throws IOException { final List < String > fn = new ArrayList < > ( ) ; try ( BufferedReader reader = ( BufferedReader ) StreamExtensions . getReader ( file , encoding , false ) ) { String line = null ; do { line = reader . readLine ( ) ; if ( line == null ) { break ; } fn . add ( line ) ; } while ( true ) ; } catch ( final IOException e ) { throw e ; } return fn ; }
Reads every line from the given File into a List and returns the List .
17,290
public static String [ ] sortData ( final File csvData , final String encoding ) throws FileNotFoundException , IOException { final List < String > fn = new ArrayList < > ( ) ; try ( BufferedReader reader = ( BufferedReader ) StreamExtensions . getReader ( csvData , encoding , false ) ) { String line = null ; int index , last ; do { line = reader . readLine ( ) ; if ( line == null ) { break ; } last = 0 ; index = line . indexOf ( ',' ) ; while ( index != - 1 ) { final String firstname = line . substring ( last , index ) . trim ( ) ; fn . add ( firstname ) ; last = index + 1 ; index = line . indexOf ( ',' , last ) ; } } while ( true ) ; } catch ( final IOException e ) { throw e ; } final String data [ ] = fn . toArray ( new String [ fn . size ( ) ] ) ; Arrays . sort ( data ) ; return data ; }
Read an csv - file and puts them in a String - array .
17,291
public static void storeFilelistToProperties ( final File output , final File input , final String comments ) throws IOException { final Properties prop = readFilelistToProperties ( input ) ; try ( final OutputStream out = StreamExtensions . getOutputStream ( output , true ) ) { prop . store ( out , comments ) ; } final OutputStream out = StreamExtensions . getOutputStream ( output , true ) ; prop . store ( out , comments ) ; }
Stores a komma seperated file to a properties object . As key is the number from the counter .
17,292
public static void writeLinesToFile ( final Collection < String > collection , final File output , final String encoding ) throws IOException { final StringBuffer sb = new StringBuffer ( ) ; for ( final String element : collection ) { sb . append ( element ) ; sb . append ( "\n" ) ; } WriteFileExtensions . writeStringToFile ( output , sb . toString ( ) , encoding ) ; }
Writes all the String - object in the collection into the given file .
17,293
public void uploadRepository ( String name , File archive ) throws ClientException { HttpPut putMethod = new HttpPut ( baseUri + "/repository/" + encodeURIComponent ( name ) ) ; HttpEntity httpEntity = MultipartEntityBuilder . create ( ) . addBinaryBody ( "file" , archive , ContentType . create ( "application/zip" ) , archive . getName ( ) ) . build ( ) ; putMethod . setEntity ( httpEntity ) ; try { CloseableHttpResponse result = httpClient . execute ( putMethod ) ; try { StatusLine status = result . getStatusLine ( ) ; if ( status . getStatusCode ( ) != HttpStatus . SC_CREATED ) { throw new APICallException ( EntityUtils . toString ( result . getEntity ( ) ) , status . getStatusCode ( ) ) ; } } finally { result . close ( ) ; } } catch ( HttpResponseException e ) { throw new APICallException ( e . getMessage ( ) , e . getStatusCode ( ) ) ; } catch ( IOException e ) { throw new NotAvailableException ( e ) ; } }
Creates or updates repository by the given name
17,294
public void initServletSession ( Task servletTask ) { String strTrxID = servletTask . getProperty ( TrxMessageHeader . LOG_TRX_ID ) ; if ( strTrxID != null ) { MessageLogModel recMessageLog = ( MessageLogModel ) Record . makeRecordFromClassName ( MessageLog . THICK_CLASS , ( RecordOwner ) servletTask . getApplication ( ) . getSystemRecordOwner ( ) ) ; try { recMessageLog = recMessageLog . getMessageLog ( strTrxID ) ; if ( recMessageLog != null ) { servletTask . setProperty ( TrxMessageHeader . LOG_TRX_ID , strTrxID ) ; String strHTMLScreen = recMessageLog . getProperty ( "screen" ) ; if ( strHTMLScreen != null ) servletTask . setProperty ( DBParams . SCREEN , strHTMLScreen ) ; } } finally { recMessageLog . free ( ) ; } } }
Do any of the initial servlet stuff .
17,295
public void add ( int i , int j , double v ) { consumer . set ( i , j , supplier . get ( i , j ) + v ) ; }
Aij + = v
17,296
public void sub ( int i , int j , double v ) { consumer . set ( i , j , supplier . get ( i , j ) - v ) ; }
Aij - = v
17,297
public void scalarMultiply ( double c ) { int m = rows ; int n = cols ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { consumer . set ( i , j , c * supplier . get ( i , j ) ) ; } } }
Scalar multiplies each item with c
17,298
public DoubleMatrix multiply ( double c ) { DoubleMatrix clone = clone ( ) ; clone . scalarMultiply ( c ) ; return clone ; }
Return new DoubleMatrix which is copy of this DoubleMatrix with each item scalar multiplied with c .
17,299
public void swapRows ( int r1 , int r2 ) { int n = columns ( ) ; ItemSupplier s = supplier ; ItemConsumer c = consumer ; for ( int j = 0 ; j < n ; j ++ ) { double v = s . get ( r1 , j ) ; c . set ( r1 , j , s . get ( r2 , j ) ) ; c . set ( r2 , j , v ) ; } }
Swaps row r1 and r2