idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
145,200 | public static String stripHtml ( String html ) { if ( html == null ) { return null ; } Element el = DOM . createDiv ( ) ; el . setInnerHTML ( html ) ; return el . getInnerText ( ) ; } | Returns the text content to any HTML . | 53 | 8 |
145,201 | public void setUserInfo ( String username , String infoName , String value ) throws CmsException { CmsUser user = m_cms . readUser ( username ) ; user . setAdditionalInfo ( infoName , value ) ; m_cms . writeUser ( user ) ; } | Sets a string - valued additional info entry on the user . | 59 | 13 |
145,202 | public void setTimewarpInt ( String timewarp ) { try { m_userSettings . setTimeWarp ( Long . valueOf ( timewarp ) . longValue ( ) ) ; } catch ( Exception e ) { m_userSettings . setTimeWarp ( - 1 ) ; } } | Sets the timewarp setting from a numeric string | 65 | 11 |
145,203 | String buildSelect ( String htmlAttributes , SelectOptions options ) { return buildSelect ( htmlAttributes , options . getOptions ( ) , options . getValues ( ) , options . getSelectedIndex ( ) ) ; } | Builds the HTML code for a select widget given a bean containing the select options | 45 | 16 |
145,204 | private String getValueFromProp ( final String propValue ) { String value = propValue ; // remove quotes value = value . trim ( ) ; if ( ( value . startsWith ( "\"" ) && value . endsWith ( "\"" ) ) || ( value . startsWith ( "'" ) && value . endsWith ( "'" ) ) ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } return value ; } | Helper to read a line from the config file . | 98 | 10 |
145,205 | public String getDynamicValue ( String attribute ) { return null == m_dynamicValues ? null : m_dynamicValues . get ( attribute ) ; } | Get cached value that is dynamically loaded by the Acacia content editor . | 33 | 14 |
145,206 | public void setDynamicValue ( String attribute , String value ) { if ( null == m_dynamicValues ) { m_dynamicValues = new ConcurrentHashMap < String , String > ( ) ; } m_dynamicValues . put ( attribute , value ) ; } | Set cached value for the attribute . Used for dynamically loaded values in the Acacia content editor . | 58 | 19 |
145,207 | public static CmsPair < String , Map < String , String > > parseEmbeddedGalleryOptions ( String configuration ) { final Map < String , String > galleryOptions = Maps . newHashMap ( ) ; String resultConfig = CmsStringUtil . substitute ( PATTERN_EMBEDDED_GALLERY_CONFIG , configuration , new I_CmsRegexSubstitution ( ) { public String substituteMatch ( String string , Matcher matcher ) { String galleryName = string . substring ( matcher . start ( 1 ) , matcher . end ( 1 ) ) ; String embeddedConfig = string . substring ( matcher . start ( 2 ) , matcher . end ( 2 ) ) ; galleryOptions . put ( galleryName , embeddedConfig ) ; return galleryName ; } } ) ; return CmsPair . create ( resultConfig , galleryOptions ) ; } | Parses and removes embedded gallery configuration strings . | 189 | 10 |
145,208 | private void updateScaling ( ) { List < I_CmsTransform > transforms = new ArrayList <> ( ) ; CmsCroppingParamBean crop = m_croppingProvider . get ( ) ; CmsImageInfoBean info = m_imageInfoProvider . get ( ) ; double wv = m_image . getElement ( ) . getParentElement ( ) . getOffsetWidth ( ) ; double hv = m_image . getElement ( ) . getParentElement ( ) . getOffsetHeight ( ) ; if ( crop == null ) { transforms . add ( new CmsBoxFit ( CmsBoxFit . Mode . scaleOnlyIfNecessary , wv , hv , info . getWidth ( ) , info . getHeight ( ) ) ) ; } else { int wt , ht ; wt = crop . getTargetWidth ( ) >= 0 ? crop . getTargetWidth ( ) : info . getWidth ( ) ; ht = crop . getTargetHeight ( ) >= 0 ? crop . getTargetHeight ( ) : info . getHeight ( ) ; transforms . add ( new CmsBoxFit ( CmsBoxFit . Mode . scaleOnlyIfNecessary , wv , hv , wt , ht ) ) ; if ( crop . isCropped ( ) ) { transforms . add ( new CmsBoxFit ( CmsBoxFit . Mode . scaleAlways , wt , ht , crop . getCropWidth ( ) , crop . getCropHeight ( ) ) ) ; transforms . add ( new CmsTranslate ( crop . getCropX ( ) , crop . getCropY ( ) ) ) ; } else { transforms . add ( new CmsBoxFit ( CmsBoxFit . Mode . scaleAlways , wt , ht , crop . getOrgWidth ( ) , crop . getOrgHeight ( ) ) ) ; } } CmsCompositeTransform chain = new CmsCompositeTransform ( transforms ) ; m_coordinateTransform = chain ; if ( ( crop == null ) || ! crop . isCropped ( ) ) { m_region = transformRegionBack ( m_coordinateTransform , CmsRectangle . fromLeftTopWidthHeight ( 0 , 0 , info . getWidth ( ) , info . getHeight ( ) ) ) ; } else { m_region = transformRegionBack ( m_coordinateTransform , CmsRectangle . fromLeftTopWidthHeight ( crop . getCropX ( ) , crop . getCropY ( ) , crop . getCropWidth ( ) , crop . getCropHeight ( ) ) ) ; } } | Sets up the coordinate transformations between the coordinate system of the parent element of the image element and the native coordinate system of the original image . | 566 | 28 |
145,209 | public static String getEncoding ( CmsObject cms , CmsResource file ) { CmsProperty encodingProperty = CmsProperty . getNullProperty ( ) ; try { encodingProperty = cms . readPropertyObject ( file , CmsPropertyDefinition . PROPERTY_CONTENT_ENCODING , true ) ; } catch ( CmsException e ) { LOG . debug ( e . getLocalizedMessage ( ) , e ) ; } return CmsEncoder . lookupEncoding ( encodingProperty . getValue ( "" ) , OpenCms . getSystemInfo ( ) . getDefaultEncoding ( ) ) ; } | Returns the encoding of the file . Encoding is read from the content - encoding property and defaults to the systems default encoding . Since properties can change without rewriting content the actual encoding can differ . | 132 | 38 |
145,210 | public String getEditorParameter ( CmsObject cms , String editor , String param ) { String path = OpenCms . getSystemInfo ( ) . getConfigFilePath ( cms , "editors/" + editor + ".properties" ) ; CmsVfsMemoryObjectCache cache = CmsVfsMemoryObjectCache . getVfsMemoryObjectCache ( ) ; CmsParameterConfiguration config = ( CmsParameterConfiguration ) cache . getCachedObject ( cms , path ) ; if ( config == null ) { try { CmsFile file = cms . readFile ( path ) ; try ( ByteArrayInputStream input = new ByteArrayInputStream ( file . getContents ( ) ) ) { config = new CmsParameterConfiguration ( input ) ; // Uses ISO-8859-1, should be OK for config parameters cache . putCachedObject ( cms , path , config ) ; } } catch ( CmsVfsResourceNotFoundException e ) { return null ; } catch ( Exception e ) { LOG . error ( e . getLocalizedMessage ( ) , e ) ; return null ; } } return config . getString ( param , null ) ; } | Gets the value of a global editor configuration parameter . | 248 | 11 |
145,211 | public Date getEnd ( ) { if ( null != m_explicitEnd ) { return isWholeDay ( ) ? adjustForWholeDay ( m_explicitEnd , true ) : m_explicitEnd ; } if ( ( null == m_end ) && ( m_series . getInstanceDuration ( ) != null ) ) { m_end = new Date ( m_start . getTime ( ) + m_series . getInstanceDuration ( ) . longValue ( ) ) ; } return isWholeDay ( ) && ! m_series . isWholeDay ( ) ? adjustForWholeDay ( m_end , true ) : m_end ; } | Returns the end time of the event . | 144 | 8 |
145,212 | public void setEnd ( Date endDate ) { if ( ( null == endDate ) || getStart ( ) . after ( endDate ) ) { m_explicitEnd = null ; } else { m_explicitEnd = endDate ; } } | Explicitly set the end time of the event . | 53 | 11 |
145,213 | private Date adjustForWholeDay ( Date date , boolean isEnd ) { Calendar result = new GregorianCalendar ( ) ; result . setTime ( date ) ; result . set ( Calendar . HOUR_OF_DAY , 0 ) ; result . set ( Calendar . MINUTE , 0 ) ; result . set ( Calendar . SECOND , 0 ) ; result . set ( Calendar . MILLISECOND , 0 ) ; if ( isEnd ) { result . add ( Calendar . DATE , 1 ) ; } return result . getTime ( ) ; } | Adjust the date according to the whole day options . | 117 | 10 |
145,214 | private boolean isSingleMultiDay ( ) { long duration = getEnd ( ) . getTime ( ) - getStart ( ) . getTime ( ) ; if ( duration > I_CmsSerialDateValue . DAY_IN_MILLIS ) { return true ; } if ( isWholeDay ( ) && ( duration <= I_CmsSerialDateValue . DAY_IN_MILLIS ) ) { return false ; } Calendar start = new GregorianCalendar ( ) ; start . setTime ( getStart ( ) ) ; Calendar end = new GregorianCalendar ( ) ; end . setTime ( getEnd ( ) ) ; if ( start . get ( Calendar . DAY_OF_MONTH ) == end . get ( Calendar . DAY_OF_MONTH ) ) { return false ; } return true ; } | Returns a flag indicating if the current event is a multi - day event . The method is only called if the single event has an explicitely set end date or an explicitely changed whole day option . | 174 | 42 |
145,215 | public static void checkCreateUpload ( CmsObject cms , CmsUgcConfiguration config , String name , long size ) throws CmsUgcException { if ( ! config . getUploadParentFolder ( ) . isPresent ( ) ) { String message = Messages . get ( ) . container ( Messages . ERR_NO_UPLOADS_ALLOWED_0 ) . key ( cms . getRequestContext ( ) . getLocale ( ) ) ; throw new CmsUgcException ( CmsUgcConstants . ErrorCode . errNoUploadAllowed , message ) ; } if ( config . getMaxUploadSize ( ) . isPresent ( ) ) { if ( config . getMaxUploadSize ( ) . get ( ) . longValue ( ) < size ) { String message = Messages . get ( ) . container ( Messages . ERR_UPLOAD_TOO_BIG_1 , name ) . key ( cms . getRequestContext ( ) . getLocale ( ) ) ; throw new CmsUgcException ( CmsUgcConstants . ErrorCode . errMaxUploadSizeExceeded , message ) ; } } if ( config . getValidExtensions ( ) . isPresent ( ) ) { List < String > validExtensions = config . getValidExtensions ( ) . get ( ) ; boolean foundExtension = false ; for ( String extension : validExtensions ) { if ( name . toLowerCase ( ) . endsWith ( extension . toLowerCase ( ) ) ) { foundExtension = true ; break ; } } if ( ! foundExtension ) { String message = Messages . get ( ) . container ( Messages . ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1 , name ) . key ( cms . getRequestContext ( ) . getLocale ( ) ) ; throw new CmsUgcException ( CmsUgcConstants . ErrorCode . errInvalidExtension , message ) ; } } } | Checks whether an uploaded file can be created in the VFS and throws an exception otherwise . | 427 | 19 |
145,216 | protected void addFacetPart ( CmsSolrQuery query ) { StringBuffer value = new StringBuffer ( ) ; value . append ( "{!key=" ) . append ( m_config . getName ( ) ) ; addFacetOptions ( value ) ; if ( m_config . getIgnoreAllFacetFilters ( ) || ( ! m_state . getCheckedEntries ( ) . isEmpty ( ) && ! m_config . getIsAndFacet ( ) ) ) { value . append ( " ex=" ) . append ( m_config . getIgnoreTags ( ) ) ; } value . append ( "}" ) ; value . append ( m_config . getRange ( ) ) ; query . add ( "facet.range" , value . toString ( ) ) ; } | Generate query part for the facet without filters . | 172 | 10 |
145,217 | private void setFittingWeekDay ( Calendar date ) { date . set ( Calendar . DAY_OF_MONTH , 1 ) ; int weekDayFirst = date . get ( Calendar . DAY_OF_WEEK ) ; int firstFittingWeekDay = ( ( ( m_weekDay . toInt ( ) + I_CmsSerialDateValue . NUM_OF_WEEKDAYS ) - weekDayFirst ) % I_CmsSerialDateValue . NUM_OF_WEEKDAYS ) + 1 ; int fittingWeekDay = firstFittingWeekDay + ( I_CmsSerialDateValue . NUM_OF_WEEKDAYS * m_weekOfMonth . ordinal ( ) ) ; if ( fittingWeekDay > date . getActualMaximum ( Calendar . DAY_OF_MONTH ) ) { fittingWeekDay -= I_CmsSerialDateValue . NUM_OF_WEEKDAYS ; } date . set ( Calendar . DAY_OF_MONTH , fittingWeekDay ) ; } | Adjusts the day in the provided month that it fits the specified week day . If there s no match for that provided month the next possible month is checked . | 216 | 32 |
145,218 | public VerticalLayout getEmptyLayout ( ) { m_emptyLayout = CmsVaadinUtils . getInfoLayout ( CmsOuTreeType . USER . getEmptyMessageKey ( ) ) ; setVisible ( size ( ) > 0 ) ; m_emptyLayout . setVisible ( size ( ) == 0 ) ; return m_emptyLayout ; } | Layout which gets displayed if table is empty . | 77 | 9 |
145,219 | public List < CmsUser > getVisibleUser ( ) { if ( ! m_fullyLoaded ) { return m_users ; } if ( size ( ) == m_users . size ( ) ) { return m_users ; } List < CmsUser > directs = new ArrayList < CmsUser > ( ) ; for ( CmsUser user : m_users ) { if ( ! m_indirects . contains ( user ) ) { directs . add ( user ) ; } } return directs ; } | Gets currently visible user . | 110 | 6 |
145,220 | String getStatus ( CmsUser user , boolean disabled , boolean newUser ) { if ( disabled ) { return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_DISABLED_0 ) ; } if ( newUser ) { return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_INACTIVE_0 ) ; } if ( OpenCms . getLoginManager ( ) . isUserTempDisabled ( user . getName ( ) ) ) { return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_UNLOCK_USER_STATUS_0 ) ; } if ( isUserPasswordReset ( user ) ) { return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_PASSWORT_RESET_0 ) ; } return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_ACTIVE_0 ) ; } | Returns status message . | 226 | 4 |
145,221 | String getStatusHelp ( CmsUser user , boolean disabled , boolean newUser ) { if ( disabled ) { return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_DISABLED_HELP_0 ) ; } if ( newUser ) { return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_INACTIVE_HELP_0 ) ; } if ( isUserPasswordReset ( user ) ) { return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_PASSWORT_RESET_HELP_0 ) ; } long lastLogin = user . getLastlogin ( ) ; return CmsVaadinUtils . getMessageText ( Messages . GUI_USERMANAGEMENT_USER_ACTIVE_HELP_1 , CmsDateUtil . getDateTime ( new Date ( lastLogin ) , DateFormat . SHORT , A_CmsUI . get ( ) . getLocale ( ) ) ) ; } | Returns status help message . | 235 | 5 |
145,222 | boolean isUserPasswordReset ( CmsUser user ) { if ( USER_PASSWORD_STATUS . containsKey ( user . getId ( ) ) ) { //Check if user was checked before if ( ! USER_PASSWORD_STATUS . get ( user . getId ( ) ) . booleanValue ( ) ) { // was false before, false->true is never done without changing map return false ; } if ( m_checkedUserPasswordReset . contains ( user . getId ( ) ) ) { //was true before, true->false happens when user resets password. Only check one time per table load. return true ; //Set gets flushed on reloading table } } CmsUser currentUser = user ; if ( user . getAdditionalInfo ( ) . size ( ) < 3 ) { try { currentUser = m_cms . readUser ( user . getId ( ) ) ; } catch ( CmsException e ) { LOG . error ( "Can not read user" , e ) ; } } if ( currentUser . getAdditionalInfo ( CmsUserSettings . ADDITIONAL_INFO_PASSWORD_RESET ) != null ) { USER_PASSWORD_STATUS . put ( currentUser . getId ( ) , new Boolean ( true ) ) ; m_checkedUserPasswordReset . add ( currentUser . getId ( ) ) ; return true ; } USER_PASSWORD_STATUS . put ( currentUser . getId ( ) , new Boolean ( false ) ) ; return false ; } | Is the user password reset? | 331 | 6 |
145,223 | private void addFoldersToSearchIn ( final List < String > folders ) { if ( null == folders ) { return ; } for ( String folder : folders ) { if ( ! CmsResource . isFolder ( folder ) ) { folder += "/" ; } m_foldersToSearchIn . add ( folder ) ; } } | Adds folders to perform the search in . | 71 | 8 |
145,224 | private void setSearchScopeFilter ( CmsObject cms ) { final List < String > searchRoots = CmsSearchUtil . computeScopeFolders ( cms , this ) ; // If the resource types contain the type "function" also // add "/system/modules/" to the search path if ( ( null != getResourceTypes ( ) ) && containsFunctionType ( getResourceTypes ( ) ) ) { searchRoots . add ( "/system/modules/" ) ; } addFoldersToSearchIn ( searchRoots ) ; } | Sets the search scope . | 116 | 6 |
145,225 | private String dbProp ( String name ) { String dbType = m_setupBean . getDatabase ( ) ; Object prop = m_setupBean . getDatabaseProperties ( ) . get ( dbType ) . get ( dbType + "." + name ) ; if ( prop == null ) { return "" ; } return prop . toString ( ) ; } | Accesses a property from the DB configuration for the selected DB . | 77 | 13 |
145,226 | protected void add ( Widget child , Element container ) { // Detach new child. child . removeFromParent ( ) ; // Logical attach. getChildren ( ) . add ( child ) ; // Physical attach. DOM . appendChild ( container , child . getElement ( ) ) ; // Adopt. adopt ( child ) ; } | Adds a new child widget to the panel attaching its Element to the specified container Element . | 70 | 17 |
145,227 | protected int adjustIndex ( Widget child , int beforeIndex ) { checkIndexBoundsForInsertion ( beforeIndex ) ; // Check to see if this widget is already a direct child. if ( child . getParent ( ) == this ) { // If the Widget's previous position was left of the desired new position // shift the desired position left to reflect the removal int idx = getWidgetIndex ( child ) ; if ( idx < beforeIndex ) { beforeIndex -- ; } } return beforeIndex ; } | Adjusts beforeIndex to account for the possibility that the given widget is already a child of this panel . | 107 | 21 |
145,228 | protected void beginDragging ( MouseDownEvent event ) { m_dragging = true ; m_windowWidth = Window . getClientWidth ( ) ; m_clientLeft = Document . get ( ) . getBodyOffsetLeft ( ) ; m_clientTop = Document . get ( ) . getBodyOffsetTop ( ) ; DOM . setCapture ( getElement ( ) ) ; m_dragStartX = event . getX ( ) ; m_dragStartY = event . getY ( ) ; addStyleName ( I_CmsLayoutBundle . INSTANCE . dialogCss ( ) . dragging ( ) ) ; } | Called on mouse down in the caption area begins the dragging loop by turning on event capture . | 134 | 19 |
145,229 | protected void endDragging ( MouseUpEvent event ) { m_dragging = false ; DOM . releaseCapture ( getElement ( ) ) ; removeStyleName ( I_CmsLayoutBundle . INSTANCE . dialogCss ( ) . dragging ( ) ) ; } | Called on mouse up in the caption area ends dragging by ending event capture . | 57 | 16 |
145,230 | public Map < String , String > getParams ( ) { Map < String , String > params = new HashMap <> ( 1 ) ; params . put ( PARAM_COLLAPSED , Boolean . TRUE . toString ( ) ) ; return params ; } | Add the option specifying if the categories should be displayed collapsed when the dialog opens . | 56 | 16 |
145,231 | public static boolean updatingIndexNecessesary ( CmsObject cms ) { // Set request to the offline project. setCmsOfflineProject ( cms ) ; // Check whether the spellcheck index directories are empty. // If they are, the index has to be built obviously. if ( isSolrSpellcheckIndexDirectoryEmpty ( ) ) { return true ; } // Compare the most recent date of a dictionary with the oldest timestamp // that determines when an index has been built. long dateMostRecentDictionary = getMostRecentDate ( cms ) ; long dateOldestIndexWrite = getOldestIndexDate ( cms ) ; return dateMostRecentDictionary > dateOldestIndexWrite ; } | Checks whether a built of the indices is necessary . | 147 | 11 |
145,232 | private static String getSolrSpellcheckRfsPath ( ) { String sPath = OpenCms . getSystemInfo ( ) . getWebInfRfsPath ( ) ; if ( ! OpenCms . getSystemInfo ( ) . getWebInfRfsPath ( ) . endsWith ( File . separator ) ) { sPath += File . separator ; } return sPath + "solr" + File . separator + "spellcheck" + File . separator + "data" ; } | Returns the path in the RFS where the Solr spellcheck files reside . | 107 | 16 |
145,233 | private static void readAndAddDocumentsFromStream ( final SolrClient client , final String lang , final InputStream is , final List < SolrInputDocument > documents , final boolean closeStream ) { final BufferedReader br = new BufferedReader ( new InputStreamReader ( is ) ) ; try { String line = br . readLine ( ) ; while ( null != line ) { final SolrInputDocument document = new SolrInputDocument ( ) ; // Each field is named after the schema "entry_xx" where xx denotes // the two digit language code. See the file spellcheck/conf/schema.xml. document . addField ( "entry_" + lang , line ) ; documents . add ( document ) ; // Prevent OutOfMemoryExceptions ... if ( documents . size ( ) >= MAX_LIST_SIZE ) { addDocuments ( client , documents , false ) ; documents . clear ( ) ; } line = br . readLine ( ) ; } } catch ( IOException e ) { LOG . error ( "Could not read spellcheck dictionary from input stream." ) ; } catch ( SolrServerException e ) { LOG . error ( "Error while adding documents to Solr server. " ) ; } finally { try { if ( closeStream ) { br . close ( ) ; } } catch ( Exception e ) { // Nothing to do here anymore .... } } } | Parses the dictionary from an InputStream . | 290 | 10 |
145,234 | private static void setCmsOfflineProject ( CmsObject cms ) { if ( null == cms ) { return ; } final CmsRequestContext cmsContext = cms . getRequestContext ( ) ; final CmsProject cmsProject = cmsContext . getCurrentProject ( ) ; if ( cmsProject . isOnlineProject ( ) ) { CmsProject cmsOfflineProject ; try { cmsOfflineProject = cms . readProject ( "Offline" ) ; cmsContext . setCurrentProject ( cmsOfflineProject ) ; } catch ( CmsException e ) { LOG . warn ( "Could not set the current project to \"Offline\". " ) ; } } } | Sets the appropriate OpenCms context . | 147 | 9 |
145,235 | private String toPath ( String name , IconSize size ) { return CmsStringUtil . joinPaths ( CmsWorkplace . getSkinUri ( ) , ICON_FOLDER , "" + name . hashCode ( ) ) + size . getSuffix ( ) ; } | Transforms user name and icon size into the image path . | 63 | 12 |
145,236 | private String toRfsName ( String name , IconSize size ) { return CmsStringUtil . joinPaths ( m_cache . getRepositoryPath ( ) , "" + name . hashCode ( ) ) + size . getSuffix ( ) ; } | Transforms user name and icon size into the rfs image path . | 57 | 14 |
145,237 | private I_CmsSearchIndex getIndex ( ) { I_CmsSearchIndex index = null ; // get the configured index or the selected index if ( isInitialCall ( ) ) { // the search form is in the initial state // get the configured index index = OpenCms . getSearchManager ( ) . getIndex ( getSettings ( ) . getUserSettings ( ) . getWorkplaceSearchIndexName ( ) ) ; } else { // the search form is not in the inital state, the submit button was used already or the // search index was changed already // get the selected index in the search dialog index = OpenCms . getSearchManager ( ) . getIndex ( getJsp ( ) . getRequest ( ) . getParameter ( "indexName.0" ) ) ; } return index ; } | Gets the index to use in the search . | 171 | 10 |
145,238 | public void transform ( String name , String transform ) throws Exception { File configFile = new File ( m_configDir , name ) ; File transformFile = new File ( m_xsltDir , transform ) ; try ( InputStream stream = new FileInputStream ( transformFile ) ) { StreamSource source = new StreamSource ( stream ) ; transform ( configFile , source ) ; } } | Transforms a config file with an XSLT transform . | 81 | 12 |
145,239 | public void transformConfig ( ) throws Exception { List < TransformEntry > entries = readTransformEntries ( new File ( m_xsltDir , "transforms.xml" ) ) ; for ( TransformEntry entry : entries ) { transform ( entry . getConfigFile ( ) , entry . getXslt ( ) ) ; } m_isDone = true ; } | Transforms the configuration . | 77 | 5 |
145,240 | public String validationErrors ( ) { List < String > errors = new ArrayList <> ( ) ; for ( File config : getConfigFiles ( ) ) { String filename = config . getName ( ) ; try ( FileInputStream stream = new FileInputStream ( config ) ) { CmsXmlUtils . unmarshalHelper ( CmsFileUtil . readFully ( stream , false ) , new CmsXmlEntityResolver ( null ) , true ) ; } catch ( CmsXmlException e ) { errors . add ( filename + ":" + e . getCause ( ) . getMessage ( ) ) ; } catch ( Exception e ) { errors . add ( filename + ":" + e . getMessage ( ) ) ; } } if ( errors . size ( ) == 0 ) { return null ; } String errString = CmsStringUtil . listAsString ( errors , "\n" ) ; JSONObject obj = new JSONObject ( ) ; try { obj . put ( "err" , errString ) ; } catch ( JSONException e ) { } return obj . toString ( ) ; } | Gets validation errors either as a JSON string or null if there are no validation errors . | 239 | 18 |
145,241 | private List < File > getConfigFiles ( ) { String [ ] filenames = { "opencms-modules.xml" , "opencms-system.xml" , "opencms-vfs.xml" , "opencms-importexport.xml" , "opencms-sites.xml" , "opencms-variables.xml" , "opencms-scheduler.xml" , "opencms-workplace.xml" , "opencms-search.xml" } ; List < File > result = new ArrayList <> ( ) ; for ( String fn : filenames ) { File file = new File ( m_configDir , fn ) ; if ( file . exists ( ) ) { result . add ( file ) ; } } return result ; } | Gets existing config files . | 167 | 6 |
145,242 | private List < TransformEntry > readTransformEntries ( File file ) throws Exception { List < TransformEntry > result = new ArrayList <> ( ) ; try ( FileInputStream fis = new FileInputStream ( file ) ) { byte [ ] data = CmsFileUtil . readFully ( fis , false ) ; Document doc = CmsXmlUtils . unmarshalHelper ( data , null , false ) ; for ( Node node : doc . selectNodes ( "//transform" ) ) { Element elem = ( ( Element ) node ) ; String xslt = elem . attributeValue ( "xslt" ) ; String conf = elem . attributeValue ( "config" ) ; TransformEntry entry = new TransformEntry ( conf , xslt ) ; result . add ( entry ) ; } } return result ; } | Reads entries from transforms . xml . | 180 | 8 |
145,243 | private void transform ( File file , Source transformSource ) throws TransformerConfigurationException , IOException , SAXException , TransformerException , ParserConfigurationException { Transformer transformer = m_transformerFactory . newTransformer ( transformSource ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "us-ascii" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "4" ) ; String configDirPath = m_configDir . getAbsolutePath ( ) ; configDirPath = configDirPath . replaceFirst ( "[/\\\\]$" , "" ) ; transformer . setParameter ( "configDir" , configDirPath ) ; XMLReader reader = m_parserFactory . newSAXParser ( ) . getXMLReader ( ) ; reader . setEntityResolver ( NO_ENTITY_RESOLVER ) ; Source source ; if ( file . exists ( ) ) { source = new SAXSource ( reader , new InputSource ( file . getCanonicalPath ( ) ) ) ; } else { source = new SAXSource ( reader , new InputSource ( new ByteArrayInputStream ( DEFAULT_XML . getBytes ( "UTF-8" ) ) ) ) ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; Result target = new StreamResult ( baos ) ; transformer . transform ( source , target ) ; byte [ ] transformedConfig = baos . toByteArray ( ) ; try ( FileOutputStream output = new FileOutputStream ( file ) ) { output . write ( transformedConfig ) ; } } | Transforms a single configuration file using the given transformation source . | 368 | 12 |
145,244 | public List < CmsJspNavElement > getSubNavigation ( ) { if ( m_subNavigation == null ) { if ( m_resource . isFile ( ) ) { m_subNavigation = Collections . emptyList ( ) ; } else if ( m_navContext == null ) { try { throw new Exception ( "Can not get subnavigation because navigation context is not set." ) ; } catch ( Exception e ) { LOG . warn ( e . getLocalizedMessage ( ) , e ) ; m_subNavigation = Collections . emptyList ( ) ; } } else { CmsJspNavBuilder navBuilder = m_navContext . getNavBuilder ( ) ; m_subNavigation = navBuilder . getNavigationForFolder ( navBuilder . getCmsObject ( ) . getSitePath ( m_resource ) , m_navContext . getVisibility ( ) , m_navContext . getFilter ( ) ) ; } } return m_subNavigation ; } | Gets the sub - entries of the navigation entry . | 213 | 11 |
145,245 | private Map < String , String > getLocaleProperties ( ) { if ( m_localeProperties == null ) { m_localeProperties = CmsCollectionsGenericWrapper . createLazyMap ( new CmsProperty . CmsPropertyLocaleTransformer ( m_properties , m_locale ) ) ; } return m_localeProperties ; } | Helper to get locale specific properties . | 81 | 7 |
145,246 | public void setEveryWorkingDay ( final boolean isEveryWorkingDay ) { if ( m_model . isEveryWorkingDay ( ) != isEveryWorkingDay ) { removeExceptionsOnChange ( new Command ( ) { public void execute ( ) { m_model . setEveryWorkingDay ( Boolean . valueOf ( isEveryWorkingDay ) ) ; m_model . setInterval ( getPatternDefaultValues ( ) . getInterval ( ) ) ; onValueChange ( ) ; } } ) ; } } | Set the everyWorkingDay flag . | 106 | 7 |
145,247 | private void removeListener ( CmsUUID listenerId ) { getRequest ( ) . getSession ( ) . removeAttribute ( SESSION_ATTRIBUTE_LISTENER_ID ) ; m_listeners . remove ( listenerId ) ; } | Remove the listener active in this session . | 53 | 8 |
145,248 | private Map < String , String > parseAttributes ( I_CmsXmlContentLocation formatterLoc ) { Map < String , String > result = new LinkedHashMap <> ( ) ; for ( I_CmsXmlContentValueLocation mappingLoc : formatterLoc . getSubValues ( N_ATTRIBUTE ) ) { String key = CmsConfigurationReader . getString ( m_cms , mappingLoc . getSubValue ( N_KEY ) ) ; String value = CmsConfigurationReader . getString ( m_cms , mappingLoc . getSubValue ( N_VALUE ) ) ; result . put ( key , value ) ; } return Collections . unmodifiableMap ( result ) ; } | Parses formatter attributes . | 150 | 7 |
145,249 | public Set < String > getConfiguredWorkplaceBundles ( ) { CmsADEConfigData configData = internalLookupConfiguration ( null , null ) ; return configData . getConfiguredWorkplaceBundles ( ) ; } | Returns the names of the bundles configured as workplace bundles in any module configuration . | 52 | 15 |
145,250 | public static String removeOpenCmsContext ( final String path ) { String context = OpenCms . getSystemInfo ( ) . getOpenCmsContext ( ) ; if ( path . startsWith ( context + "/" ) ) { return path . substring ( context . length ( ) ) ; } String renderPrefix = OpenCms . getStaticExportManager ( ) . getVfsPrefix ( ) ; if ( path . startsWith ( renderPrefix + "/" ) ) { return path . substring ( renderPrefix . length ( ) ) ; } return path ; } | Given a path to a VFS resource the method removes the OpenCms context in case the path is prefixed by that context . | 123 | 27 |
145,251 | public String getPermalink ( CmsObject cms , String resourceName , CmsUUID detailContentId ) { String permalink = "" ; try { permalink = substituteLink ( cms , CmsPermalinkResourceHandler . PERMALINK_HANDLER ) ; String id = cms . readResource ( resourceName , CmsResourceFilter . ALL ) . getStructureId ( ) . toString ( ) ; permalink += id ; if ( detailContentId != null ) { permalink += ":" + detailContentId ; } String ext = CmsFileUtil . getExtension ( resourceName ) ; if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( ext ) ) { permalink += ext ; } CmsSite currentSite = OpenCms . getSiteManager ( ) . getCurrentSite ( cms ) ; String serverPrefix = null ; if ( currentSite == OpenCms . getSiteManager ( ) . getDefaultSite ( ) ) { Optional < CmsSite > siteForDefaultUri = OpenCms . getSiteManager ( ) . getSiteForDefaultUri ( ) ; if ( siteForDefaultUri . isPresent ( ) ) { serverPrefix = siteForDefaultUri . get ( ) . getServerPrefix ( cms , resourceName ) ; } else { serverPrefix = OpenCms . getSiteManager ( ) . getWorkplaceServer ( ) ; } } else { serverPrefix = currentSite . getServerPrefix ( cms , resourceName ) ; } if ( ! permalink . startsWith ( serverPrefix ) ) { permalink = serverPrefix + permalink ; } } catch ( CmsException e ) { // if something wrong permalink = e . getLocalizedMessage ( ) ; if ( LOG . isErrorEnabled ( ) ) { LOG . error ( e . getLocalizedMessage ( ) , e ) ; } } return permalink ; } | Returns the perma link for the given resource and optional detail content . <p< | 416 | 17 |
145,252 | public String getPermalinkForCurrentPage ( CmsObject cms ) { return getPermalink ( cms , cms . getRequestContext ( ) . getUri ( ) , cms . getRequestContext ( ) . getDetailContentId ( ) ) ; } | Returns the perma link for the current page based on the URI and detail content id stored in the CmsObject passed as a parameter . <p< | 58 | 31 |
145,253 | public String getWorkplaceLink ( CmsObject cms , String resourceName , boolean forceSecure ) { String result = substituteLinkForUnknownTarget ( cms , resourceName , forceSecure ) ; return appendServerPrefix ( cms , result , resourceName , true ) ; } | Returns the link for the given workplace resource . | 59 | 9 |
145,254 | private Table buildTable ( CmsSqlConsoleResults results ) { IndexedContainer container = new IndexedContainer ( ) ; int numCols = results . getColumns ( ) . size ( ) ; for ( int c = 0 ; c < numCols ; c ++ ) { container . addContainerProperty ( Integer . valueOf ( c ) , results . getColumnType ( c ) , null ) ; } int r = 0 ; for ( List < Object > row : results . getData ( ) ) { Item item = container . addItem ( Integer . valueOf ( r ) ) ; for ( int c = 0 ; c < numCols ; c ++ ) { item . getItemProperty ( Integer . valueOf ( c ) ) . setValue ( row . get ( c ) ) ; } r += 1 ; } Table table = new Table ( ) ; table . setContainerDataSource ( container ) ; for ( int c = 0 ; c < numCols ; c ++ ) { String col = ( results . getColumns ( ) . get ( c ) ) ; table . setColumnHeader ( Integer . valueOf ( c ) , col ) ; } table . setWidth ( "100%" ) ; table . setHeight ( "100%" ) ; table . setColumnCollapsingAllowed ( true ) ; return table ; } | Builds the table for the database results . | 282 | 9 |
145,255 | private void updateImageInfo ( ) { String crop = getCrop ( ) ; String point = getPoint ( ) ; m_imageInfoDisplay . fillContent ( m_info , crop , point ) ; } | Updates the image information . | 44 | 6 |
145,256 | public static CmsShell getTopShell ( ) { ArrayList < CmsShell > shells = SHELL_STACK . get ( ) ; if ( shells . isEmpty ( ) ) { return null ; } return shells . get ( shells . size ( ) - 1 ) ; } | Gets the top of thread - local shell stack or null if it is empty . | 59 | 17 |
145,257 | public static void popShell ( ) { ArrayList < CmsShell > shells = SHELL_STACK . get ( ) ; if ( shells . size ( ) > 0 ) { shells . remove ( shells . size ( ) - 1 ) ; } } | Removes top of thread - local shell stack . | 53 | 10 |
145,258 | public static CmsSearchConfigurationSorting create ( final String sortParam , final List < I_CmsSearchConfigurationSortOption > options , final I_CmsSearchConfigurationSortOption defaultOption ) { return ( null != sortParam ) || ( ( null != options ) && ! options . isEmpty ( ) ) || ( null != defaultOption ) ? new CmsSearchConfigurationSorting ( sortParam , options , defaultOption ) : null ; } | Creates a sort configuration iff at least one of the parameters is not null and the options list is not empty . | 93 | 24 |
145,259 | public static CmsResourceTypeStatResultList init ( CmsResourceTypeStatResultList resList ) { if ( resList == null ) { return new CmsResourceTypeStatResultList ( ) ; } resList . deleteOld ( ) ; return resList ; } | Method to initialize the list . | 56 | 6 |
145,260 | protected boolean exportWithMinimalMetaData ( String path ) { String checkPath = path . startsWith ( "/" ) ? path + "/" : "/" + path + "/" ; for ( String p : m_parameters . getResourcesToExportWithMetaData ( ) ) { if ( checkPath . startsWith ( p ) ) { return false ; } } return true ; } | Check if the resource should be exported with minimal meta - data . This holds for resources that are not part of the export but must be exported as super - folders . | 81 | 33 |
145,261 | @ Override public void setDraggable ( Element elem , String draggable ) { super . setDraggable ( elem , draggable ) ; if ( "true" . equals ( draggable ) ) { elem . getStyle ( ) . setProperty ( "webkitUserDrag" , "element" ) ; } else { elem . getStyle ( ) . clearProperty ( "webkitUserDrag" ) ; } } | Webkit based browsers require that we set the webkit - user - drag style attribute to make an element draggable . | 94 | 25 |
145,262 | protected void createParentXmlElements ( CmsXmlContent xmlContent , String xmlPath , Locale l ) { if ( CmsXmlUtils . isDeepXpath ( xmlPath ) ) { String parentPath = CmsXmlUtils . removeLastXpathElement ( xmlPath ) ; if ( null == xmlContent . getValue ( parentPath , l ) ) { createParentXmlElements ( xmlContent , parentPath , l ) ; xmlContent . addValue ( m_cms , parentPath , l , CmsXmlUtils . getXpathIndexInt ( parentPath ) - 1 ) ; } } } | Creates the parents of nested XML elements if necessary . | 137 | 11 |
145,263 | public byte [ ] join ( Map < Integer , byte [ ] > parts ) { checkArgument ( parts . size ( ) > 0 , "No parts provided" ) ; final int [ ] lengths = parts . values ( ) . stream ( ) . mapToInt ( v -> v . length ) . distinct ( ) . toArray ( ) ; checkArgument ( lengths . length == 1 , "Varying lengths of part values" ) ; final byte [ ] secret = new byte [ lengths [ 0 ] ] ; for ( int i = 0 ; i < secret . length ; i ++ ) { final byte [ ] [ ] points = new byte [ parts . size ( ) ] [ 2 ] ; int j = 0 ; for ( Map . Entry < Integer , byte [ ] > part : parts . entrySet ( ) ) { points [ j ] [ 0 ] = part . getKey ( ) . byteValue ( ) ; points [ j ] [ 1 ] = part . getValue ( ) [ i ] ; j ++ ; } secret [ i ] = GF256 . interpolate ( points ) ; } return secret ; } | Joins the given parts to recover the original secret . | 234 | 11 |
145,264 | public static Processor < DataSinkTask > sink ( DataSink dataSink , int parallelism , String description , UserConfig taskConf , ActorSystem system ) { io . gearpump . streaming . Processor < DataSinkTask > p = DataSinkProcessor . apply ( dataSink , parallelism , description , taskConf , system ) ; return new Processor ( p ) ; } | Creates a Sink Processor | 83 | 6 |
145,265 | public static Processor < DataSourceTask > source ( DataSource source , int parallelism , String description , UserConfig taskConf , ActorSystem system ) { io . gearpump . streaming . Processor < DataSourceTask < Object , Object > > p = DataSourceProcessor . apply ( source , parallelism , description , taskConf , system ) ; return new Processor ( p ) ; } | Creates a Source Processor | 80 | 5 |
145,266 | @ Override public Token recoverInline ( Parser recognizer ) throws RecognitionException { // SINGLE TOKEN DELETION Token matchedSymbol = singleTokenDeletion ( recognizer ) ; if ( matchedSymbol != null ) { // we have deleted the extra token. // now, move past ttype token as if all were ok recognizer . consume ( ) ; return matchedSymbol ; } // SINGLE TOKEN INSERTION if ( singleTokenInsertion ( recognizer ) ) { return getMissingSymbol ( recognizer ) ; } // BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR); // exception.pushToken(this.getGrammarToken(recognizer.getCurrentToken())); // throw exception; throw new InputMismatchException ( recognizer ) ; } | Make sure we don t attempt to recover inline ; if the parser successfully recovers it won t throw an exception . | 182 | 22 |
145,267 | protected DirectiveStatement parseDirectiveStatement ( DirectiveStContext node ) { DirectiveStContext stContext = ( DirectiveStContext ) node ; DirectiveExpContext direExp = stContext . directiveExp ( ) ; Token token = direExp . Identifier ( ) . getSymbol ( ) ; String directive = token . getText ( ) . toLowerCase ( ) . intern ( ) ; TerminalNode value = direExp . StringLiteral ( ) ; List < TerminalNode > idNodeList = null ; DirectiveExpIDListContext directExpidLisCtx = direExp . directiveExpIDList ( ) ; if ( directExpidLisCtx != null ) { idNodeList = directExpidLisCtx . Identifier ( ) ; } Set < String > idList = null ; DirectiveStatement ds = null ; if ( value != null ) { String idListValue = this . getStringValue ( value . getText ( ) ) ; idList = new HashSet ( Arrays . asList ( idListValue . split ( "," ) ) ) ; ds = new DirectiveStatement ( directive , idList , this . getBTToken ( token ) ) ; } else if ( idNodeList != null ) { idList = new HashSet < String > ( ) ; for ( TerminalNode t : idNodeList ) { idList . add ( t . getText ( ) ) ; } ds = new DirectiveStatement ( directive , idList , this . getBTToken ( token ) ) ; } else { ds = new DirectiveStatement ( directive , Collections . EMPTY_SET , this . getBTToken ( token ) ) ; } if ( directive . equals ( "dynamic" ) ) { if ( ds . getIdList ( ) . size ( ) == 0 ) { data . allDynamic = true ; } else { data . dynamicObjectSet = ds . getIdList ( ) ; } ds = new DirectiveStatement ( directive , Collections . EMPTY_SET , this . getBTToken ( token ) ) ; return ds ; } else if ( directive . equalsIgnoreCase ( "safe_output_open" . intern ( ) ) ) { this . pbCtx . isSafeOutput = true ; return ds ; } else if ( directive . equalsIgnoreCase ( "safe_output_close" . intern ( ) ) ) { this . pbCtx . isSafeOutput = false ; return ds ; } else { return ds ; } } | directive dynamic xxx yy | 530 | 7 |
145,268 | public static NamingConvention determineNamingConvention ( TypeElement type , Iterable < ExecutableElement > methods , Messager messager , Types types ) { ExecutableElement beanMethod = null ; ExecutableElement prefixlessMethod = null ; for ( ExecutableElement method : methods ) { switch ( methodNameConvention ( method ) ) { case BEAN : beanMethod = firstNonNull ( beanMethod , method ) ; break ; case PREFIXLESS : prefixlessMethod = firstNonNull ( prefixlessMethod , method ) ; break ; default : break ; } } if ( prefixlessMethod != null ) { if ( beanMethod != null ) { messager . printMessage ( ERROR , "Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '" + beanMethod . getSimpleName ( ) + "' and '" + prefixlessMethod . getSimpleName ( ) + "'" , type ) ; } return new PrefixlessConvention ( messager , types ) ; } else { return new BeanConvention ( messager , types ) ; } } | Determine whether the user has followed bean - like naming convention or not . | 231 | 16 |
145,269 | public SourceBuilder add ( String fmt , Object ... args ) { TemplateApplier . withParams ( args ) . onText ( source :: append ) . onParam ( this :: add ) . parse ( fmt ) ; return this ; } | Appends formatted text to the source . | 49 | 8 |
145,270 | public SourceBuilder addLine ( String fmt , Object ... args ) { add ( fmt , args ) ; source . append ( LINE_SEPARATOR ) ; return this ; } | Appends a formatted line of code to the source . | 36 | 11 |
145,271 | private Map < StandardMethod , UnderrideLevel > findUnderriddenMethods ( Iterable < ExecutableElement > methods ) { Map < StandardMethod , ExecutableElement > standardMethods = new LinkedHashMap <> ( ) ; for ( ExecutableElement method : methods ) { Optional < StandardMethod > standardMethod = maybeStandardMethod ( method ) ; if ( standardMethod . isPresent ( ) && isUnderride ( method ) ) { standardMethods . put ( standardMethod . get ( ) , method ) ; } } if ( standardMethods . containsKey ( StandardMethod . EQUALS ) != standardMethods . containsKey ( StandardMethod . HASH_CODE ) ) { ExecutableElement underriddenMethod = standardMethods . containsKey ( StandardMethod . EQUALS ) ? standardMethods . get ( StandardMethod . EQUALS ) : standardMethods . get ( StandardMethod . HASH_CODE ) ; messager . printMessage ( ERROR , "hashCode and equals must be implemented together on FreeBuilder types" , underriddenMethod ) ; } ImmutableMap . Builder < StandardMethod , UnderrideLevel > result = ImmutableMap . builder ( ) ; for ( StandardMethod standardMethod : standardMethods . keySet ( ) ) { if ( standardMethods . get ( standardMethod ) . getModifiers ( ) . contains ( Modifier . FINAL ) ) { result . put ( standardMethod , UnderrideLevel . FINAL ) ; } else { result . put ( standardMethod , UnderrideLevel . OVERRIDEABLE ) ; } } return result . build ( ) ; } | Find any standard methods the user has underridden in their type . | 324 | 13 |
145,272 | private boolean hasToBuilderMethod ( DeclaredType builder , boolean isExtensible , Iterable < ExecutableElement > methods ) { for ( ExecutableElement method : methods ) { if ( isToBuilderMethod ( builder , method ) ) { if ( ! isExtensible ) { messager . printMessage ( ERROR , "No accessible no-args Builder constructor available to implement toBuilder" , method ) ; } return true ; } } return false ; } | Find a toBuilder method if the user has provided one . | 94 | 12 |
145,273 | private String generatedBuilderSimpleName ( TypeElement type ) { String packageName = elements . getPackageOf ( type ) . getQualifiedName ( ) . toString ( ) ; String originalName = type . getQualifiedName ( ) . toString ( ) ; checkState ( originalName . startsWith ( packageName + "." ) ) ; String nameWithoutPackage = originalName . substring ( packageName . length ( ) + 1 ) ; return String . format ( BUILDER_SIMPLE_NAME_TEMPLATE , nameWithoutPackage . replaceAll ( "\\." , "_" ) ) ; } | Returns the simple name of the builder class that should be generated for the given type . | 129 | 17 |
145,274 | public static void addToString ( SourceBuilder code , Datatype datatype , Map < Property , PropertyCodeGenerator > generatorsByProperty , boolean forPartial ) { String typename = ( forPartial ? "partial " : "" ) + datatype . getType ( ) . getSimpleName ( ) ; Predicate < PropertyCodeGenerator > isOptional = generator -> { Initially initially = generator . initialState ( ) ; return ( initially == Initially . OPTIONAL || ( initially == Initially . REQUIRED && forPartial ) ) ; } ; boolean anyOptional = generatorsByProperty . values ( ) . stream ( ) . anyMatch ( isOptional ) ; boolean allOptional = generatorsByProperty . values ( ) . stream ( ) . allMatch ( isOptional ) && ! generatorsByProperty . isEmpty ( ) ; code . addLine ( "" ) . addLine ( "@%s" , Override . class ) . addLine ( "public %s toString() {" , String . class ) ; if ( allOptional ) { bodyWithBuilderAndSeparator ( code , datatype , generatorsByProperty , typename ) ; } else if ( anyOptional ) { bodyWithBuilder ( code , datatype , generatorsByProperty , typename , isOptional ) ; } else { bodyWithConcatenation ( code , generatorsByProperty , typename ) ; } code . addLine ( "}" ) ; } | Generates a toString method using concatenation or a StringBuilder . | 302 | 15 |
145,275 | private static void bodyWithConcatenation ( SourceBuilder code , Map < Property , PropertyCodeGenerator > generatorsByProperty , String typename ) { code . add ( " return \"%s{" , typename ) ; String prefix = "" ; for ( Property property : generatorsByProperty . keySet ( ) ) { PropertyCodeGenerator generator = generatorsByProperty . get ( property ) ; code . add ( "%s%s=\" + %s + \"" , prefix , property . getName ( ) , ( Excerpt ) generator :: addToStringValue ) ; prefix = ", " ; } code . add ( "}\";%n" ) ; } | Generate the body of a toString method that uses plain concatenation . | 139 | 16 |
145,276 | private static void bodyWithBuilder ( SourceBuilder code , Datatype datatype , Map < Property , PropertyCodeGenerator > generatorsByProperty , String typename , Predicate < PropertyCodeGenerator > isOptional ) { Variable result = new Variable ( "result" ) ; code . add ( " %1$s %2$s = new %1$s(\"%3$s{" , StringBuilder . class , result , typename ) ; boolean midStringLiteral = true ; boolean midAppends = true ; boolean prependCommas = false ; PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty . values ( ) . stream ( ) . filter ( isOptional ) . reduce ( ( first , second ) -> second ) . get ( ) ; for ( Property property : generatorsByProperty . keySet ( ) ) { PropertyCodeGenerator generator = generatorsByProperty . get ( property ) ; if ( isOptional . test ( generator ) ) { if ( midStringLiteral ) { code . add ( "\")" ) ; } if ( midAppends ) { code . add ( ";%n " ) ; } code . add ( "if (" ) ; if ( generator . initialState ( ) == Initially . OPTIONAL ) { generator . addToStringCondition ( code ) ; } else { code . add ( "!%s.contains(%s.%s)" , UNSET_PROPERTIES , datatype . getPropertyEnum ( ) , property . getAllCapsName ( ) ) ; } code . add ( ") {%n %s.append(\"" , result ) ; if ( prependCommas ) { code . add ( ", " ) ; } code . add ( "%s=\").append(%s)" , property . getName ( ) , property . getField ( ) ) ; if ( ! prependCommas ) { code . add ( ".append(\", \")" ) ; } code . add ( ";%n }%n " ) ; if ( generator . equals ( lastOptionalGenerator ) ) { code . add ( "return %s.append(\"" , result ) ; midStringLiteral = true ; midAppends = true ; } else { midStringLiteral = false ; midAppends = false ; } } else { if ( ! midAppends ) { code . add ( "%s" , result ) ; } if ( ! midStringLiteral ) { code . add ( ".append(\"" ) ; } if ( prependCommas ) { code . add ( ", " ) ; } code . add ( "%s=\").append(%s)" , property . getName ( ) , ( Excerpt ) generator :: addToStringValue ) ; midStringLiteral = false ; midAppends = true ; prependCommas = true ; } } checkState ( prependCommas , "Unexpected state at end of toString method" ) ; checkState ( midAppends , "Unexpected state at end of toString method" ) ; if ( ! midStringLiteral ) { code . add ( ".append(\"" ) ; } code . add ( "}\").toString();%n" , result ) ; } | Generates the body of a toString method that uses a StringBuilder . | 694 | 15 |
145,277 | private static void bodyWithBuilderAndSeparator ( SourceBuilder code , Datatype datatype , Map < Property , PropertyCodeGenerator > generatorsByProperty , String typename ) { Variable result = new Variable ( "result" ) ; Variable separator = new Variable ( "separator" ) ; code . addLine ( " %1$s %2$s = new %1$s(\"%3$s{\");" , StringBuilder . class , result , typename ) ; if ( generatorsByProperty . size ( ) > 1 ) { // If there's a single property, we don't actually use the separator variable code . addLine ( " %s %s = \"\";" , String . class , separator ) ; } Property first = generatorsByProperty . keySet ( ) . iterator ( ) . next ( ) ; Property last = getLast ( generatorsByProperty . keySet ( ) ) ; for ( Property property : generatorsByProperty . keySet ( ) ) { PropertyCodeGenerator generator = generatorsByProperty . get ( property ) ; switch ( generator . initialState ( ) ) { case HAS_DEFAULT : throw new RuntimeException ( "Internal error: unexpected default field" ) ; case OPTIONAL : code . addLine ( " if (%s) {" , ( Excerpt ) generator :: addToStringCondition ) ; break ; case REQUIRED : code . addLine ( " if (!%s.contains(%s.%s)) {" , UNSET_PROPERTIES , datatype . getPropertyEnum ( ) , property . getAllCapsName ( ) ) ; break ; } code . add ( " " ) . add ( result ) ; if ( property != first ) { code . add ( ".append(%s)" , separator ) ; } code . add ( ".append(\"%s=\").append(%s)" , property . getName ( ) , ( Excerpt ) generator :: addToStringValue ) ; if ( property != last ) { code . add ( ";%n %s = \", \"" , separator ) ; } code . add ( ";%n }%n" ) ; } code . addLine ( " return %s.append(\"}\").toString();" , result ) ; } | Generates the body of a toString method that uses a StringBuilder and a separator variable . | 489 | 20 |
145,278 | public static void addLazyDefinitions ( SourceBuilder code ) { Set < Declaration > defined = new HashSet <> ( ) ; // Definitions may lazily declare new names; ensure we add them all List < Declaration > declarations = code . scope ( ) . keysOfType ( Declaration . class ) . stream ( ) . sorted ( ) . collect ( toList ( ) ) ; while ( ! defined . containsAll ( declarations ) ) { for ( Declaration declaration : declarations ) { if ( defined . add ( declaration ) ) { code . add ( code . scope ( ) . get ( declaration ) . definition ) ; } } declarations = code . scope ( ) . keysOfType ( Declaration . class ) . stream ( ) . sorted ( ) . collect ( toList ( ) ) ; } } | Finds all lazily - declared classes and methods and adds their definitions to the source . | 164 | 18 |
145,279 | public void addPartialFieldAssignment ( SourceBuilder code , Excerpt finalField , String builder ) { addFinalFieldAssignment ( code , finalField , builder ) ; } | Add the final assignment of the property to the partial value object s source code . | 37 | 16 |
145,280 | public static void addActionsTo ( SourceBuilder code , Set < MergeAction > mergeActions , boolean forBuilder ) { SetMultimap < String , String > nounsByVerb = TreeMultimap . create ( ) ; mergeActions . forEach ( mergeAction -> { if ( forBuilder || ! mergeAction . builderOnly ) { nounsByVerb . put ( mergeAction . verb , mergeAction . noun ) ; } } ) ; List < String > verbs = ImmutableList . copyOf ( nounsByVerb . keySet ( ) ) ; String lastVerb = getLast ( verbs , null ) ; for ( String verb : nounsByVerb . keySet ( ) ) { code . add ( ", %s%s" , ( verbs . size ( ) > 1 && verb . equals ( lastVerb ) ) ? "and " : "" , verb ) ; List < String > nouns = ImmutableList . copyOf ( nounsByVerb . get ( verb ) ) ; for ( int i = 0 ; i < nouns . size ( ) ; ++ i ) { String separator = ( i == 0 ) ? "" : ( i == nouns . size ( ) - 1 ) ? " and" : "," ; code . add ( "%s %s" , separator , nouns . get ( i ) ) ; } } } | Emits a sentence fragment combining all the merge actions . | 294 | 11 |
145,281 | public static Variable upcastToGeneratedBuilder ( SourceBuilder code , Datatype datatype , String builder ) { return code . scope ( ) . computeIfAbsent ( Declaration . UPCAST , ( ) -> { Variable base = new Variable ( "base" ) ; code . addLine ( UPCAST_COMMENT ) . addLine ( "%s %s = %s;" , datatype . getGeneratedBuilder ( ) , base , builder ) ; return base ; } ) ; } | Upcasts a Builder instance to the generated superclass to allow access to private fields . | 106 | 17 |
145,282 | public static Optional < Variable > freshBuilder ( SourceBuilder code , Datatype datatype ) { if ( ! datatype . getBuilderFactory ( ) . isPresent ( ) ) { return Optional . empty ( ) ; } return Optional . of ( code . scope ( ) . computeIfAbsent ( Declaration . FRESH_BUILDER , ( ) -> { Variable defaults = new Variable ( "defaults" ) ; code . addLine ( "%s %s = %s;" , datatype . getGeneratedBuilder ( ) , defaults , datatype . getBuilderFactory ( ) . get ( ) . newBuilder ( datatype . getBuilder ( ) , TypeInference . INFERRED_TYPES ) ) ; return defaults ; } ) ) ; } | Declares a fresh Builder to copy default property values from . | 164 | 12 |
145,283 | public JavadocLink javadocMethodLink ( String memberName , Type ... types ) { return new JavadocLink ( "%s#%s(%s)" , getQualifiedName ( ) , memberName , ( Excerpt ) code -> { String separator = "" ; for ( Type type : types ) { code . add ( "%s%s" , separator , type . getQualifiedName ( ) ) ; separator = ", " ; } } ) ; } | Returns a source excerpt of a JavaDoc link to a method on this type . | 103 | 16 |
145,284 | public Excerpt typeParameters ( ) { if ( getTypeParameters ( ) . isEmpty ( ) ) { return Excerpts . EMPTY ; } else { return Excerpts . add ( "<%s>" , Excerpts . join ( ", " , getTypeParameters ( ) ) ) ; } } | Returns a source excerpt of the type parameters of this type including angle brackets . Always an empty string if the type class is not generic . | 64 | 27 |
145,285 | protected Violation createViolation ( Integer lineNumber , String sourceLine , String message ) { Violation violation = new Violation ( ) ; violation . setRule ( this ) ; violation . setSourceLine ( sourceLine ) ; violation . setLineNumber ( lineNumber ) ; violation . setMessage ( message ) ; return violation ; } | Create and return a new Violation for this rule and the specified values | 69 | 14 |
145,286 | protected Violation createViolation ( SourceCode sourceCode , ASTNode node , String message ) { String sourceLine = sourceCode . line ( node . getLineNumber ( ) - 1 ) ; return createViolation ( node . getLineNumber ( ) , sourceLine , message ) ; } | Create a new Violation for the AST node . | 60 | 10 |
145,287 | protected Violation createViolationForImport ( SourceCode sourceCode , ImportNode importNode , String message ) { Map importInfo = ImportUtil . sourceLineAndNumberForImport ( sourceCode , importNode ) ; Violation violation = new Violation ( ) ; violation . setRule ( this ) ; violation . setSourceLine ( ( String ) importInfo . get ( "sourceLine" ) ) ; violation . setLineNumber ( ( Integer ) importInfo . get ( "lineNumber" ) ) ; violation . setMessage ( message ) ; return violation ; } | Create and return a new Violation for this rule and the specified import | 117 | 14 |
145,288 | protected Violation createViolationForImport ( SourceCode sourceCode , String className , String alias , String violationMessage ) { Map importInfo = ImportUtil . sourceLineAndNumberForImport ( sourceCode , className , alias ) ; Violation violation = new Violation ( ) ; violation . setRule ( this ) ; violation . setSourceLine ( ( String ) importInfo . get ( "sourceLine" ) ) ; violation . setLineNumber ( ( Integer ) importInfo . get ( "lineNumber" ) ) ; violation . setMessage ( violationMessage ) ; return violation ; } | Create and return a new Violation for this rule and the specified import className and alias | 123 | 18 |
145,289 | protected boolean shouldApplyThisRuleTo ( ClassNode classNode ) { // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns boolean shouldApply = true ; String applyTo = getApplyToClassNames ( ) ; String doNotApplyTo = getDoNotApplyToClassNames ( ) ; if ( applyTo != null && applyTo . length ( ) > 0 ) { WildcardPattern pattern = new WildcardPattern ( applyTo , true ) ; shouldApply = pattern . matches ( classNode . getNameWithoutPackage ( ) ) || pattern . matches ( classNode . getName ( ) ) ; } if ( shouldApply && doNotApplyTo != null && doNotApplyTo . length ( ) > 0 ) { WildcardPattern pattern = new WildcardPattern ( doNotApplyTo , true ) ; shouldApply = ! pattern . matches ( classNode . getNameWithoutPackage ( ) ) && ! pattern . matches ( classNode . getName ( ) ) ; } return shouldApply ; } | Return true if this rule should be applied for the specified ClassNode based on the configuration of this rule . | 212 | 21 |
145,290 | public Results analyze ( RuleSet ruleSet ) { long startTime = System . currentTimeMillis ( ) ; DirectoryResults reportResults = new DirectoryResults ( ) ; int numThreads = Runtime . getRuntime ( ) . availableProcessors ( ) - 1 ; numThreads = numThreads > 0 ? numThreads : 1 ; ExecutorService pool = Executors . newFixedThreadPool ( numThreads ) ; for ( FileSet fileSet : fileSets ) { processFileSet ( fileSet , ruleSet , pool ) ; } pool . shutdown ( ) ; try { boolean completed = pool . awaitTermination ( POOL_TIMEOUT_SECONDS , TimeUnit . SECONDS ) ; if ( ! completed ) { throw new IllegalStateException ( "Thread Pool terminated before comp<FileResults>letion" ) ; } } catch ( InterruptedException e ) { throw new IllegalStateException ( "Thread Pool interrupted before completion" ) ; } addDirectoryResults ( reportResults ) ; LOG . info ( "Analysis time=" + ( System . currentTimeMillis ( ) - startTime ) + "ms" ) ; return reportResults ; } | Analyze all source code using the specified RuleSet and return the report results . | 244 | 16 |
145,291 | private static boolean isPredefinedConstant ( Expression expression ) { if ( expression instanceof PropertyExpression ) { Expression object = ( ( PropertyExpression ) expression ) . getObjectExpression ( ) ; Expression property = ( ( PropertyExpression ) expression ) . getProperty ( ) ; if ( object instanceof VariableExpression ) { List < String > predefinedConstantNames = PREDEFINED_CONSTANTS . get ( ( ( VariableExpression ) object ) . getName ( ) ) ; if ( predefinedConstantNames != null && predefinedConstantNames . contains ( property . getText ( ) ) ) { return true ; } } } return false ; } | Tells you if the expression is a predefined constant like TRUE or FALSE . | 144 | 16 |
145,292 | public static boolean isMapLiteralWithOnlyConstantValues ( Expression expression ) { if ( expression instanceof MapExpression ) { List < MapEntryExpression > entries = ( ( MapExpression ) expression ) . getMapEntryExpressions ( ) ; for ( MapEntryExpression entry : entries ) { if ( ! isConstantOrConstantLiteral ( entry . getKeyExpression ( ) ) || ! isConstantOrConstantLiteral ( entry . getValueExpression ( ) ) ) { return false ; } } return true ; } return false ; } | Returns true if a Map literal that contains only entries where both key and value are constants . | 123 | 18 |
145,293 | public static boolean isListLiteralWithOnlyConstantValues ( Expression expression ) { if ( expression instanceof ListExpression ) { List < Expression > expressions = ( ( ListExpression ) expression ) . getExpressions ( ) ; for ( Expression e : expressions ) { if ( ! isConstantOrConstantLiteral ( e ) ) { return false ; } } return true ; } return false ; } | Returns true if a List literal that contains only entries that are constants . | 87 | 14 |
145,294 | public static boolean isConstant ( Expression expression , Object expected ) { return expression instanceof ConstantExpression && expected . equals ( ( ( ConstantExpression ) expression ) . getValue ( ) ) ; } | Tells you if an expression is the expected constant . | 42 | 11 |
145,295 | public static List < ? extends Expression > getMethodArguments ( ASTNode methodCall ) { if ( methodCall instanceof ConstructorCallExpression ) { return extractExpressions ( ( ( ConstructorCallExpression ) methodCall ) . getArguments ( ) ) ; } else if ( methodCall instanceof MethodCallExpression ) { return extractExpressions ( ( ( MethodCallExpression ) methodCall ) . getArguments ( ) ) ; } else if ( methodCall instanceof StaticMethodCallExpression ) { return extractExpressions ( ( ( StaticMethodCallExpression ) methodCall ) . getArguments ( ) ) ; } else if ( respondsTo ( methodCall , "getArguments" ) ) { throw new RuntimeException ( ) ; // TODO: remove, should never happen } return new ArrayList < Expression > ( ) ; } | Return the List of Arguments for the specified MethodCallExpression or a ConstructorCallExpression . The returned List contains either ConstantExpression or MapEntryExpression objects . | 178 | 36 |
145,296 | public static boolean isMethodNamed ( MethodCallExpression methodCall , String methodNamePattern , Integer numArguments ) { Expression method = methodCall . getMethod ( ) ; // !important: performance enhancement boolean IS_NAME_MATCH = false ; if ( method instanceof ConstantExpression ) { if ( ( ( ConstantExpression ) method ) . getValue ( ) instanceof String ) { IS_NAME_MATCH = ( ( String ) ( ( ConstantExpression ) method ) . getValue ( ) ) . matches ( methodNamePattern ) ; } } if ( IS_NAME_MATCH && numArguments != null ) { return AstUtil . getMethodArguments ( methodCall ) . size ( ) == numArguments ; } return IS_NAME_MATCH ; } | Return true only if the MethodCallExpression represents a method call for the specified method name | 166 | 18 |
145,297 | public static boolean isConstructorCall ( Expression expression , List < String > classNames ) { return expression instanceof ConstructorCallExpression && classNames . contains ( expression . getType ( ) . getName ( ) ) ; } | Return true if the expression is a constructor call on any of the named classes with any number of parameters . | 48 | 21 |
145,298 | public static boolean isConstructorCall ( Expression expression , String classNamePattern ) { return expression instanceof ConstructorCallExpression && expression . getType ( ) . getName ( ) . matches ( classNamePattern ) ; } | Return true if the expression is a constructor call on a class that matches the supplied . | 47 | 17 |
145,299 | public static AnnotationNode getAnnotation ( AnnotatedNode node , String name ) { List < AnnotationNode > annotations = node . getAnnotations ( ) ; for ( AnnotationNode annot : annotations ) { if ( annot . getClassNode ( ) . getName ( ) . equals ( name ) ) { return annot ; } } return null ; } | Return the AnnotationNode for the named annotation or else null . Supports Groovy 1 . 5 and Groovy 1 . 6 . | 75 | 26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.