idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
2,700
protected ClassLoader initClassLoader ( String baseDirPath ) throws MalformedURLException { File webAppClasses = new File ( baseDirPath + WEB_INF_CLASSES_DIR_PATH ) ; File [ ] webAppLibs = new File ( baseDirPath + WEB_INF_LIB_DIR_PATH ) . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( JAR_FILE_EXTENSION ) ; } } ) ; int length = webAppLibs != null ? webAppLibs . length + 1 : 1 ; URL [ ] urls = new URL [ length ] ; urls [ 0 ] = webAppClasses . toURI ( ) . toURL ( ) ; for ( int i = 1 ; i < length ; i ++ ) { urls [ i ] = webAppLibs [ i - 1 ] . toURI ( ) . toURL ( ) ; } ClassLoader webAppClassLoader = new JawrBundleProcessorCustomClassLoader ( urls , getClass ( ) . getClassLoader ( ) ) ; Thread . currentThread ( ) . setContextClassLoader ( webAppClassLoader ) ; return webAppClassLoader ; }
Initialize the classloader
2,701
protected ServletContext initServletContext ( Document webXmlDoc , String baseDirPath , String tmpDirPath , String springConfigFiles , String servletAPIversion ) { MockServletContext servletContext = new MockServletContext ( servletAPIversion , baseDirPath , tmpDirPath ) ; Map < String , Object > servletContextInitParams = new HashMap < String , Object > ( ) ; NodeList contextParamsNodes = webXmlDoc . getElementsByTagName ( CONTEXT_TAG_NAME ) ; for ( int i = 0 ; i < contextParamsNodes . getLength ( ) ; i ++ ) { Node node = contextParamsNodes . item ( i ) ; initializeInitParams ( node , servletContextInitParams ) ; } if ( StringUtils . isNotEmpty ( springConfigFiles ) ) { servletContextInitParams . put ( CONFIG_LOCATION_PARAM , springConfigFiles . replace ( " " , "%20" ) ) ; } servletContext . setInitParameters ( servletContextInitParams ) ; return servletContext ; }
Initalize the servlet context
2,702
protected List < ServletDefinition > getWebXmlServletDefinitions ( Document webXmlDoc , ServletContext servletContext , List < String > servletsToInitialize , ClassLoader webAppClassLoader ) throws ClassNotFoundException { NodeList servletNodes = webXmlDoc . getElementsByTagName ( SERVLET_TAG_NAME ) ; List < ServletDefinition > servletDefinitions = new ArrayList < ServletDefinition > ( ) ; for ( int i = 0 ; i < servletNodes . getLength ( ) ; i ++ ) { String servletName = null ; Class < ? > servletClass = null ; MockServletConfig config = new MockServletConfig ( servletContext ) ; int order = i ; Node servletNode = servletNodes . item ( i ) ; Map < String , Object > initParameters = new HashMap < String , Object > ( ) ; NodeList childNodes = servletNode . getChildNodes ( ) ; for ( int j = 0 ; j < childNodes . getLength ( ) ; j ++ ) { Node servletChildNode = childNodes . item ( j ) ; if ( servletChildNode . getNodeName ( ) . equals ( SERVLET_NAME_TAG_NAME ) ) { servletName = getTextValue ( servletChildNode ) ; config . setServletName ( servletName ) ; } else if ( servletChildNode . getNodeName ( ) . equals ( SERVLET_CLASS_TAG_NAME ) ) { String servletClassName = getTextValue ( servletChildNode ) ; servletClass = webAppClassLoader . loadClass ( servletClassName ) ; } else if ( servletChildNode . getNodeName ( ) . equals ( INIT_PARAM_TAG_NAME ) ) { initializeInitParams ( servletChildNode , initParameters ) ; } else if ( servletChildNode . getNodeName ( ) . equals ( LOAD_ON_STARTUP_TAG_NAME ) ) { order = Integer . parseInt ( getTextValue ( servletChildNode ) ) ; } } config . setInitParameters ( initParameters ) ; if ( servletsToInitialize . contains ( servletName ) || JawrServlet . class . isAssignableFrom ( servletClass ) ) { ServletDefinition servletDef = new ServletDefinition ( servletClass , config , order ) ; servletDefinitions . add ( servletDef ) ; } if ( servletContext . getInitParameter ( CONFIG_LOCATION_PARAM ) == null && servletClass . getName ( ) . equals ( "org.springframework.web.servlet.DispatcherServlet" ) ) { ( ( MockServletContext ) servletContext ) . putInitParameter ( CONFIG_LOCATION_PARAM , "/WEB-INF/" + servletName + "-servlet.xml" ) ; } } return servletDefinitions ; }
Returns the list of servlet definition which must be initialize
2,703
protected List < ServletDefinition > initJawrSpringControllers ( ServletContext servletContext ) throws ServletException { SpringControllerBundleProcessor springBundleProcessor = new SpringControllerBundleProcessor ( ) ; return springBundleProcessor . initJawrSpringServlets ( servletContext ) ; }
Initialize the Jawr spring controller
2,704
protected List < ServletDefinition > initServlets ( List < ServletDefinition > servletDefinitions ) throws Exception { Collections . sort ( servletDefinitions ) ; ThreadLocalJawrContext . setBundleProcessingAtBuildTime ( true ) ; List < ServletDefinition > jawrServletDefinitions = new ArrayList < ServletDefinition > ( ) ; for ( Iterator < ServletDefinition > iterator = servletDefinitions . iterator ( ) ; iterator . hasNext ( ) ; ) { ServletDefinition servletDefinition = ( ServletDefinition ) iterator . next ( ) ; servletDefinition . initServlet ( ) ; if ( servletDefinition . isJawrServletDefinition ( ) ) { jawrServletDefinitions . add ( servletDefinition ) ; } } return jawrServletDefinitions ; }
Initialize the servlets and returns only the list of Jawr servlets
2,705
protected void initializeInitParams ( Node initParamNode , Map < String , Object > initParameters ) { String paramName = null ; String paramValue = null ; NodeList childNodes = initParamNode . getChildNodes ( ) ; for ( int j = 0 ; j < childNodes . getLength ( ) ; j ++ ) { Node childNode = childNodes . item ( j ) ; String nodeName = childNode . getNodeName ( ) ; if ( nodeName . equals ( PARAM_NAME_TAG_NAME ) ) { paramName = getTextValue ( childNode ) ; } else if ( nodeName . equals ( PARAM_VALUE_TAG_NAME ) ) { paramValue = getTextValue ( childNode ) ; } } initParameters . put ( paramName , paramValue ) ; }
Initialize the init parameters define in the servlet config
2,706
protected void processJawrServlets ( String destDirPath , List < ServletDefinition > jawrServletDefinitions , boolean keepUrlMapping ) throws Exception { String appRootDir = "" ; String jsServletMapping = "" ; String cssServletMapping = "" ; String binaryServletMapping = "" ; for ( Iterator < ServletDefinition > iterator = jawrServletDefinitions . iterator ( ) ; iterator . hasNext ( ) ; ) { ServletDefinition servletDef = ( ServletDefinition ) iterator . next ( ) ; ServletConfig servletConfig = servletDef . getServletConfig ( ) ; Map < ? , ? > initParameters = ( ( MockServletConfig ) servletConfig ) . getInitParameters ( ) ; initParameters . remove ( "jawr.config.reload.interval" ) ; String jawrServletMapping = servletConfig . getInitParameter ( JawrConstant . SERVLET_MAPPING_PROPERTY_NAME ) ; String servletMapping = servletConfig . getInitParameter ( JawrConstant . SPRING_SERVLET_MAPPING_PROPERTY_NAME ) ; if ( servletMapping == null ) { servletMapping = jawrServletMapping ; } ResourceBundlesHandler bundleHandler = null ; BinaryResourcesHandler binaryRsHandler = null ; ServletContext servletContext = servletConfig . getServletContext ( ) ; String type = servletConfig . getInitParameter ( TYPE_INIT_PARAMETER ) ; if ( type == null || type . equals ( JawrConstant . JS_TYPE ) ) { bundleHandler = ( ResourceBundlesHandler ) servletContext . getAttribute ( JawrConstant . JS_CONTEXT_ATTRIBUTE ) ; String contextPathOverride = bundleHandler . getConfig ( ) . getContextPathOverride ( ) ; if ( StringUtils . isNotEmpty ( contextPathOverride ) ) { int idx = contextPathOverride . indexOf ( "//" ) ; if ( idx != - 1 ) { idx = contextPathOverride . indexOf ( "/" , idx + 2 ) ; if ( idx != - 1 ) { appRootDir = PathNormalizer . asPath ( contextPathOverride . substring ( idx ) ) ; } } } if ( jawrServletMapping != null ) { jsServletMapping = PathNormalizer . asPath ( jawrServletMapping ) ; } } else if ( type . equals ( JawrConstant . CSS_TYPE ) ) { bundleHandler = ( ResourceBundlesHandler ) servletContext . getAttribute ( JawrConstant . CSS_CONTEXT_ATTRIBUTE ) ; if ( jawrServletMapping != null ) { cssServletMapping = PathNormalizer . asPath ( jawrServletMapping ) ; } } else if ( type . equals ( JawrConstant . BINARY_TYPE ) ) { binaryRsHandler = ( BinaryResourcesHandler ) servletContext . getAttribute ( JawrConstant . BINARY_CONTEXT_ATTRIBUTE ) ; if ( jawrServletMapping != null ) { binaryServletMapping = PathNormalizer . asPath ( jawrServletMapping ) ; } } if ( bundleHandler != null ) { createBundles ( servletDef . getServlet ( ) , bundleHandler , destDirPath , servletMapping , keepUrlMapping ) ; } else if ( binaryRsHandler != null ) { createBinaryBundle ( servletDef . getServlet ( ) , binaryRsHandler , destDirPath , servletConfig , keepUrlMapping ) ; } } createApacheRewriteConfigFile ( destDirPath , appRootDir , jsServletMapping , cssServletMapping , binaryServletMapping ) ; }
Process the Jawr Servlets
2,707
protected void createApacheRewriteConfigFile ( String cdnDestDirPath , String appRootDir , String jsServletMapping , String cssServletMapping , String imgServletMapping ) throws IOException { BufferedReader templateFileReader = null ; FileWriter fileWriter = null ; try { templateFileReader = new BufferedReader ( new InputStreamReader ( this . getClass ( ) . getResourceAsStream ( TEMPLATE_JAWR_APACHE_HTTPD_CONF_PATH ) ) ) ; fileWriter = new FileWriter ( cdnDestDirPath + File . separator + JAWR_APACHE_HTTPD_CONF_FILE ) ; String line = null ; boolean processNextString = true ; while ( ( line = templateFileReader . readLine ( ) ) != null ) { if ( line . startsWith ( CHECKS_JAWR_JS_SERVLET_MAPPING_EXISTS ) ) { if ( StringUtils . isEmpty ( jsServletMapping ) ) { processNextString = false ; } } else if ( line . startsWith ( CHECK_JAWR_CSS_SERVLET_MAPPING_EXISTS ) ) { if ( StringUtils . isEmpty ( cssServletMapping ) ) { processNextString = false ; } } else if ( processNextString == false ) { processNextString = true ; } else { line = line . replaceAll ( APP_ROOT_DIR_PATTERN , appRootDir ) ; line = line . replaceAll ( JAWR_JS_SERVLET_MAPPING_PATTERN , jsServletMapping ) ; line = line . replaceAll ( JAWR_CSS_SERVLET_MAPPING_PATTERN , cssServletMapping ) ; line = line . replaceAll ( JAWR_IMG_SERVLET_MAPPING_PATTERN , imgServletMapping ) ; fileWriter . write ( line + "\n" ) ; } } } finally { IOUtils . close ( templateFileReader ) ; IOUtils . close ( fileWriter ) ; } }
Create the apache rewrite configuration file
2,708
protected void createBundles ( HttpServlet servlet , ResourceBundlesHandler bundleHandler , String destDirPath , String servletMapping , boolean keepUrlMapping ) throws IOException , ServletException { List < JoinableResourceBundle > bundles = bundleHandler . getContextBundles ( ) ; Iterator < JoinableResourceBundle > bundleIterator = bundles . iterator ( ) ; MockServletResponse response = new MockServletResponse ( ) ; MockServletRequest request = new MockServletRequest ( JAWR_BUNDLE_PROCESSOR_CONTEXT_PATH ) ; MockServletSession session = new MockServletSession ( servlet . getServletContext ( ) ) ; request . setSession ( session ) ; String resourceType = servlet . getServletConfig ( ) . getInitParameter ( TYPE_INIT_PARAMETER ) ; if ( resourceType == null ) { resourceType = JawrConstant . JS_TYPE ; } while ( bundleIterator . hasNext ( ) ) { JoinableResourceBundle bundle = ( JoinableResourceBundle ) bundleIterator . next ( ) ; URL url = servlet . getServletContext ( ) . getResource ( bundle . getId ( ) ) ; if ( url != null ) { logger . error ( "It is not recommended to use a bundle name which could be in conflict with a resource.\n" + "Please rename your bundle '" + bundle . getId ( ) + "' to avoid any issue" ) ; } List < Map < String , String > > allVariants = VariantUtils . getAllVariants ( bundle . getVariants ( ) ) ; if ( allVariants == null ) { allVariants = new ArrayList < Map < String , String > > ( ) ; } if ( allVariants . isEmpty ( ) ) { allVariants . add ( new HashMap < String , String > ( ) ) ; } for ( Iterator < Map < String , String > > it = allVariants . iterator ( ) ; it . hasNext ( ) ; ) { Map < String , String > variantMap = ( Map < String , String > ) it . next ( ) ; List < RenderedLink > linksToBundle = createLinkToBundle ( bundleHandler , bundle . getId ( ) , resourceType , variantMap ) ; for ( Iterator < RenderedLink > iteratorLinks = linksToBundle . iterator ( ) ; iteratorLinks . hasNext ( ) ; ) { RenderedLink renderedLink = iteratorLinks . next ( ) ; String path = renderedLink . getLink ( ) ; JawrConfig config = bundleHandler . getConfig ( ) ; config . setDebugModeOn ( renderedLink . isDebugMode ( ) ) ; String finalBundlePath = null ; if ( keepUrlMapping ) { finalBundlePath = path ; } else { finalBundlePath = getFinalBundlePath ( path , config , variantMap ) ; } setRequestUrl ( request , variantMap , path , config ) ; if ( ! ( path . indexOf ( "?" ) != - 1 ) || ! keepUrlMapping ) { File bundleFile = new File ( destDirPath , finalBundlePath ) ; createBundleFile ( servlet , response , request , path , bundleFile , servletMapping ) ; } } } } }
Creates the bundles in the destination directory
2,709
protected void setRequestUrl ( MockServletRequest request , Map < String , String > variantMap , String path , JawrConfig config ) { String domainURL = JawrConstant . HTTP_URL_PREFIX + DEFAULT_WEBAPP_URL ; if ( JawrConstant . SSL . equals ( variantMap . get ( JawrConstant . CONNECTION_TYPE_VARIANT_TYPE ) ) ) { if ( StringUtils . isNotEmpty ( config . getContextPathSslOverride ( ) ) && config . getContextPathSslOverride ( ) . startsWith ( JawrConstant . HTTPS_URL_PREFIX ) ) { domainURL = config . getContextPathSslOverride ( ) ; } else { domainURL = JawrConstant . HTTPS_URL_PREFIX + DEFAULT_WEBAPP_URL ; } } else { if ( StringUtils . isNotEmpty ( config . getContextPathOverride ( ) ) && config . getContextPathOverride ( ) . startsWith ( JawrConstant . HTTP_URL_PREFIX ) ) { domainURL = config . getContextPathOverride ( ) ; } else { domainURL = JawrConstant . HTTP_URL_PREFIX + DEFAULT_WEBAPP_URL ; } } request . setRequestUrl ( PathNormalizer . joinDomainToPath ( domainURL , path ) ) ; }
Set the request URL
2,710
public String getFinalBundlePath ( String path , JawrConfig jawrConfig , Map < String , String > variantMap ) { String finalPath = path ; int jawrGenerationParamIdx = finalPath . indexOf ( JawrRequestHandler . GENERATION_PARAM ) ; if ( jawrGenerationParamIdx != - 1 ) { try { finalPath = URLDecoder . decode ( path , "UTF-8" ) ; } catch ( UnsupportedEncodingException neverHappens ) { throw new RuntimeException ( "Something went unexpectedly wrong while decoding a URL for a generator. " , neverHappens ) ; } finalPath = removeServletMappingFromPath ( finalPath , jawrConfig . getServletMapping ( ) ) ; finalPath = jawrConfig . getGeneratorRegistry ( ) . getDebugModeBuildTimeGenerationPath ( finalPath ) ; } else { finalPath = removeServletMappingFromPath ( finalPath , jawrConfig . getServletMapping ( ) ) ; if ( finalPath . startsWith ( "/" ) ) { finalPath = finalPath . substring ( 1 ) ; } if ( ! jawrConfig . isDebugModeOn ( ) ) { int idx = finalPath . indexOf ( "/" ) ; finalPath = finalPath . substring ( idx + 1 ) ; } finalPath = VariantUtils . getVariantBundleName ( finalPath , variantMap , false ) ; } return finalPath ; }
Retrieves the final path where the servlet mapping and the cache prefix have been removed and take also in account the jawr generator URLs .
2,711
public String getImageFinalPath ( String path , JawrConfig jawrConfig ) { String finalPath = path ; finalPath = removeServletMappingFromPath ( finalPath , jawrConfig . getServletMapping ( ) ) ; if ( finalPath . startsWith ( "/" ) ) { finalPath = finalPath . substring ( 1 ) ; } int idx = finalPath . indexOf ( "/" ) ; finalPath = finalPath . substring ( idx + 1 ) ; return finalPath ; }
Retrieves the image final path where the servlet mapping and the cache prefix have been removed
2,712
protected String removeServletMappingFromPath ( String path , String mapping ) { if ( mapping != null && mapping . length ( ) > 0 ) { int idx = path . indexOf ( mapping ) ; if ( idx > - 1 ) { path = path . substring ( idx + mapping . length ( ) ) ; } path = PathNormalizer . asPath ( path ) ; } return path ; }
Remove the servlet mapping from the path
2,713
protected void createBinaryBundle ( HttpServlet servlet , BinaryResourcesHandler binaryRsHandler , String destDirPath , ServletConfig servletConfig , boolean keepUrlMapping ) throws IOException , ServletException { Map < String , String > bundleImgMap = binaryRsHandler . getBinaryPathMap ( ) ; Iterator < String > bundleIterator = bundleImgMap . values ( ) . iterator ( ) ; MockServletResponse response = new MockServletResponse ( ) ; MockServletRequest request = new MockServletRequest ( JAWR_BUNDLE_PROCESSOR_CONTEXT_PATH ) ; String jawrServletMapping = servletConfig . getInitParameter ( JawrConstant . SERVLET_MAPPING_PROPERTY_NAME ) ; if ( jawrServletMapping == null ) { jawrServletMapping = "" ; } String servletMapping = servletConfig . getInitParameter ( JawrConstant . SPRING_SERVLET_MAPPING_PROPERTY_NAME ) ; if ( servletMapping == null ) { servletMapping = jawrServletMapping ; } while ( bundleIterator . hasNext ( ) ) { String path = ( String ) bundleIterator . next ( ) ; String binaryFinalPath = null ; if ( keepUrlMapping ) { binaryFinalPath = path ; } else { binaryFinalPath = getImageFinalPath ( path , binaryRsHandler . getConfig ( ) ) ; } File destFile = new File ( destDirPath , binaryFinalPath ) ; Map < String , String > variantMap = new HashMap < String , String > ( ) ; setRequestUrl ( request , variantMap , path , binaryRsHandler . getConfig ( ) ) ; path = PathNormalizer . concatWebPath ( PathNormalizer . asDirPath ( jawrServletMapping ) , path ) ; createBundleFile ( servlet , response , request , path , destFile , servletMapping ) ; } }
Create the image bundle
2,714
protected void createBundleFile ( HttpServlet servlet , MockServletResponse response , MockServletRequest request , String path , File destFile , String mapping ) throws IOException , ServletException { request . setRequestPath ( mapping , path ) ; if ( ! destFile . getParentFile ( ) . exists ( ) ) { boolean dirsCreated = destFile . getParentFile ( ) . mkdirs ( ) ; if ( ! dirsCreated ) { throw new IOException ( "The directory '" + destFile . getParentFile ( ) . getCanonicalPath ( ) + "' can't be created." ) ; } } try { response . setOutputStream ( new FileOutputStream ( destFile ) ) ; servlet . service ( request , response ) ; } finally { response . close ( ) ; } if ( destFile . length ( ) == 0 ) { logger . warn ( "No content retrieved for file '" + destFile . getAbsolutePath ( ) + "', which is associated to the path : " + path ) ; System . out . println ( "No content retrieved for file '" + destFile . getAbsolutePath ( ) + "', which is associated to the path : " + path ) ; } }
Create the bundle file
2,715
protected List < RenderedLink > createLinkToBundle ( ResourceBundlesHandler handler , String path , String resourceType , Map < String , String > variantMap ) throws IOException { ArrayList < RenderedLink > linksToBundle = new ArrayList < RenderedLink > ( ) ; BasicBundleRenderer bundleRenderer = new BasicBundleRenderer ( handler , resourceType ) ; StringWriter sw = new StringWriter ( ) ; boolean useGzip = false ; boolean isSslRequest = false ; handler . getConfig ( ) . setDebugModeOn ( false ) ; handler . getConfig ( ) . setGzipResourcesModeOn ( useGzip ) ; BundleRendererContext ctx = new BundleRendererContext ( "" , variantMap , useGzip , isSslRequest ) ; bundleRenderer . renderBundleLinks ( path , ctx , sw ) ; handler . getConfig ( ) . setDebugModeOn ( true ) ; ctx = new BundleRendererContext ( "" , variantMap , useGzip , isSslRequest ) ; bundleRenderer . renderBundleLinks ( path , ctx , sw ) ; List < RenderedLink > renderedLinks = bundleRenderer . getRenderedLinks ( ) ; String contextPathOverride = handler . getConfig ( ) . getContextPathOverride ( ) ; for ( Iterator < RenderedLink > iterator = renderedLinks . iterator ( ) ; iterator . hasNext ( ) ; ) { RenderedLink renderedLink = iterator . next ( ) ; String renderedLinkPath = renderedLink . getLink ( ) ; if ( StringUtils . isNotEmpty ( contextPathOverride ) && renderedLinkPath . startsWith ( contextPathOverride ) ) { renderedLinkPath = renderedLinkPath . substring ( contextPathOverride . length ( ) ) ; } renderedLink . setLink ( PathNormalizer . asPath ( renderedLinkPath ) ) ; linksToBundle . add ( renderedLink ) ; } return linksToBundle ; }
Returns the link to the bundle
2,716
public static FilePathMapping buildFilePathMapping ( String path , ResourceReaderHandler rsHandler ) { return buildFilePathMapping ( null , path , rsHandler ) ; }
Builds the File path mapping
2,717
public static FilePathMapping buildFilePathMapping ( JoinableResourceBundle bundle , String path , ResourceReaderHandler rsHandler ) { FilePathMapping fPathMapping = null ; String filePath = rsHandler . getFilePath ( path ) ; if ( filePath != null ) { File f = new File ( filePath ) ; if ( f . exists ( ) ) { fPathMapping = new FilePathMapping ( bundle , filePath , f . lastModified ( ) ) ; if ( bundle != null ) { bundle . getLinkedFilePathMappings ( ) . add ( fPathMapping ) ; } } else { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "The file path '" + filePath + "' associated to the URL '" + path + "' doesn't exixts." ) ; } } } return fPathMapping ; }
Builds the File path mapping and add it to the file mappings of the bundle
2,718
public StringBuffer minifyStringBuffer ( StringBuffer sb , Charset charset ) throws IOException , JSMinException { byte [ ] bundleBytes = sb . toString ( ) . getBytes ( charset . name ( ) ) ; ByteArrayInputStream bIs = new ByteArrayInputStream ( bundleBytes ) ; ByteArrayOutputStream bOs = new ByteArrayOutputStream ( ) ; JSMin minifier = new JSMin ( bIs , bOs ) ; minifier . jsmin ( ) ; byte [ ] minified = bOs . toByteArray ( ) ; return byteArrayToString ( charset , minified ) ; }
Utility method for components that need to use JSMin in a different context other than bundle postprocessing .
2,719
private StringBuffer byteArrayToString ( Charset charset , byte [ ] minified ) throws IOException { ReadableByteChannel chan = Channels . newChannel ( new ByteArrayInputStream ( minified ) ) ; Reader rd = Channels . newReader ( chan , charset . newDecoder ( ) , - 1 ) ; StringWriter writer = new StringWriter ( ) ; IOUtils . copy ( rd , writer , true ) ; return writer . getBuffer ( ) ; }
Convert a byte array to a String buffer taking into account the charset
2,720
public final static JsBundleLinkRenderer getJsBundleRenderer ( ResourceBundlesHandler bundler , String type , Boolean useRandomParam , Boolean async , Boolean defer , String crossorigin ) { JsBundleLinkRenderer renderer = ( JsBundleLinkRenderer ) ClassLoaderResourceUtils . buildObjectInstance ( bundler . getConfig ( ) . getJsBundleLinkRenderClass ( ) ) ; renderer . init ( bundler , type , useRandomParam , async , defer , crossorigin ) ; return renderer ; }
Returns the JS Bundle renderer
2,721
public final static CssBundleLinkRenderer getCssBundleRenderer ( ResourceBundlesHandler bundler , Boolean useRandomParam , String media , boolean alternate , boolean displayAlternateStyles , String title ) { CssBundleLinkRenderer renderer = ( CssBundleLinkRenderer ) ClassLoaderResourceUtils . buildObjectInstance ( bundler . getConfig ( ) . getCssBundleLinkRenderClass ( ) ) ; renderer . init ( bundler , useRandomParam , media , alternate , displayAlternateStyles , title ) ; return renderer ; }
Returns the CSS Bundle renderer
2,722
public final static ImgRenderer getImgRenderer ( JawrConfig config , boolean isPlainImg ) { ImgRenderer renderer = ( ImgRenderer ) ClassLoaderResourceUtils . buildObjectInstance ( config . getImgRendererClass ( ) ) ; renderer . init ( isPlainImg ) ; return renderer ; }
Returns the image renderer
2,723
public Reader createResource ( GeneratorContext context ) { InputStream is = createStreamResource ( context ) ; ReadableByteChannel chan = Channels . newChannel ( is ) ; return Channels . newReader ( chan , context . getCharset ( ) . newDecoder ( ) , - 1 ) ; }
Finds a resource from the classpath and returns a reader on it .
2,724
public InputStream createStreamResource ( GeneratorContext context ) { InputStream is = null ; try { String resourcePath = context . getPath ( ) ; String path = getCompletePath ( resourcePath ) ; is = ClassLoaderResourceUtils . getResourceAsStream ( path , this ) ; } catch ( FileNotFoundException e ) { throw new BundlingProcessException ( e ) ; } return is ; }
Finds a resource from the classpath and returns an input stream on it .
2,725
private String getCompletePath ( String resourcePath ) { String path = PathNormalizer . normalizePath ( classpathPrefix + resourcePath ) ; return path ; }
Returns the complete path with the classpath prefix
2,726
private Set < String > getResourceNamesFromJar ( String path , URL resourceURL ) { URLConnection con = null ; try { if ( resourceURL . toString ( ) . startsWith ( JawrConstant . JAR_URL_PREFIX ) ) { con = resourceURL . openConnection ( ) ; } } catch ( IOException e ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Unable to find resources name for path '" + path + "'" , e ) ; } return Collections . emptySet ( ) ; } JarFile jarFile ; String jarFileUrl ; String rootEntryPath ; boolean newJarFile = false ; try { if ( con instanceof JarURLConnection ) { JarURLConnection jarCon = ( JarURLConnection ) con ; jarCon . setUseCaches ( true ) ; jarFile = jarCon . getJarFile ( ) ; JarEntry jarEntry = jarCon . getJarEntry ( ) ; rootEntryPath = ( jarEntry != null ? jarEntry . getName ( ) : "" ) ; } else { String urlFile = resourceURL . getFile ( ) ; int separatorIndex = urlFile . indexOf ( JAR_URL_SEPARATOR ) ; if ( separatorIndex != - 1 ) { jarFileUrl = urlFile . substring ( 0 , separatorIndex ) ; rootEntryPath = urlFile . substring ( separatorIndex + JAR_URL_SEPARATOR . length ( ) ) ; jarFile = getJarFile ( jarFileUrl ) ; } else { jarFile = new JarFile ( urlFile ) ; rootEntryPath = "" ; } newJarFile = true ; } } catch ( IOException e ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Unable to find resources name for path '" + path + "'" , e ) ; } return Collections . emptySet ( ) ; } try { if ( ! "" . equals ( rootEntryPath ) && ! rootEntryPath . endsWith ( "/" ) ) { rootEntryPath = rootEntryPath + "/" ; } Set < String > result = new LinkedHashSet < > ( 8 ) ; for ( Enumeration < JarEntry > entries = jarFile . entries ( ) ; entries . hasMoreElements ( ) ; ) { JarEntry entry = entries . nextElement ( ) ; String entryPath = entry . getName ( ) ; if ( isDirectChildPath ( rootEntryPath , entryPath ) ) { String relativePath = entryPath . substring ( rootEntryPath . length ( ) ) ; result . add ( relativePath ) ; } } return result ; } finally { if ( newJarFile ) { try { jarFile . close ( ) ; } catch ( IOException e ) { } } } }
Returns the resources name from a Jar file .
2,727
public Map < String , List < String > > filterPathSet ( Collection < String > paths ) { Map < String , List < String > > expressions = new HashMap < > ( ) ; List < String > toRemove = new ArrayList < > ( ) ; for ( Iterator < String > it = paths . iterator ( ) ; it . hasNext ( ) ; ) { String path = it . next ( ) ; if ( COMMENTS_PATTERN . matcher ( path ) . matches ( ) ) { Matcher matcher = OPERATORS_PATTERN . matcher ( path ) ; matcher . find ( ) ; String suffix = matcher . group ( ) ; suffix = suffix . substring ( 0 , suffix . lastIndexOf ( "." ) ) ; String expressionKey = createExpressionKey ( suffix ) ; if ( expressions . containsKey ( expressionKey ) ) { List < String > fileNames = expressions . get ( expressionKey ) ; fileNames . add ( path ) ; } else { List < String > fileNames = new ArrayList < > ( ) ; fileNames . add ( path ) ; expressions . put ( expressionKey , fileNames ) ; } toRemove . add ( path ) ; } } for ( Iterator < String > it = toRemove . iterator ( ) ; it . hasNext ( ) ; ) { paths . remove ( it . next ( ) ) ; } return expressions ; }
Finds all the paths in a collection which contain IE conditional comment syntax extracts all of them from the collection .
2,728
private String createExpressionKey ( String suffix ) { String [ ] parts = suffix . split ( "_" ) ; StringBuilder ret = new StringBuilder ( "[if " ) ; boolean ieAdded = false ; for ( String part : parts ) { if ( "" . equals ( part ) ) { continue ; } if ( "ie" . equals ( part ) ) { break ; } else if ( Pattern . matches ( "(lt|lte|gt|gte)" , part ) ) { ret . append ( part ) . append ( " " ) ; } else { ret . append ( "IE " ) . append ( part ) ; ieAdded = true ; } } if ( ! ieAdded ) ret . append ( "IE" ) ; ret . append ( "]" ) ; return ret . toString ( ) ; }
Creates an IE conditional expression by transforming the suffix of a filename .
2,729
private HttpServletResponse getHttpServletResponseUrlEncoder ( final Response response ) { return new HttpServletResponse ( ) { public void setLocale ( Locale loc ) { } public void setContentType ( String type ) { } public void setContentLength ( int len ) { } public void setBufferSize ( int size ) { } public void resetBuffer ( ) { } public void reset ( ) { } public boolean isCommitted ( ) { return false ; } public PrintWriter getWriter ( ) throws IOException { return new PrintWriter ( new RedirectWriter ( getResponse ( ) ) ) ; } public ServletOutputStream getOutputStream ( ) throws IOException { return null ; } public Locale getLocale ( ) { return null ; } public int getBufferSize ( ) { return 0 ; } public void flushBuffer ( ) throws IOException { } public void setStatus ( int sc , String sm ) { } public void setStatus ( int sc ) { } public void setIntHeader ( String name , int value ) { } public void setHeader ( String name , String value ) { } public void setDateHeader ( String name , long date ) { } public void sendRedirect ( String location ) throws IOException { } public void sendError ( int sc , String msg ) throws IOException { } public void sendError ( int sc ) throws IOException { } public String encodeUrl ( String url ) { return response . encodeURL ( url ) . toString ( ) ; } public String encodeURL ( String url ) { return response . encodeURL ( url ) . toString ( ) ; } public String encodeRedirectUrl ( String url ) { return null ; } public String encodeRedirectURL ( String url ) { return null ; } public boolean containsHeader ( String name ) { return false ; } public void addIntHeader ( String name , int value ) { } public void addHeader ( String name , String value ) { } public void addDateHeader ( String name , long date ) { } public void addCookie ( Cookie cookie ) { } public String getContentType ( ) { return null ; } public void setCharacterEncoding ( String charset ) { } public String getCharacterEncoding ( ) { return "UTF-8" ; } } ; }
Returns the HttpServletResponse which will be used to encode the URL
2,730
private void addLinkedResource ( FilePathMapping linkedResource ) { linkedResources . add ( linkedResource ) ; if ( parent != null ) { parent . addLinkedResource ( linkedResource ) ; } }
Adds a linked resource to the less source
2,731
private Reader getResourceReader ( String resource ) throws ResourceNotFoundException { List < Class < ? > > excluded = new ArrayList < > ( ) ; excluded . add ( ILessCssResourceGenerator . class ) ; return rsReaderHandler . getResource ( bundle , resource , false , excluded ) ; }
Returns the resource reader
2,732
public String getFinalFullBundlePath ( BundleProcessingStatus status ) { JawrConfig jawrConfig = status . getJawrConfig ( ) ; String bundleName = status . getCurrentBundle ( ) . getId ( ) ; String bundlePrefix = getBundlePrefix ( status , jawrConfig , bundleName ) ; String fullBundlePath = PathNormalizer . concatWebPath ( bundlePrefix , bundleName ) ; return fullBundlePath ; }
Returns the full path for the CSS bundle taking in account the css servlet path if defined the caching prefix and the url context path overridden
2,733
protected String getBundlePrefix ( BundleProcessingStatus status , JawrConfig jawrConfig , String bundleName ) { String bundlePrefix = status . getCurrentBundle ( ) . getBundlePrefix ( ) ; if ( bundlePrefix == null ) { bundlePrefix = "" ; } else { bundlePrefix = PathNormalizer . asPath ( bundlePrefix ) ; } if ( ! bundleName . equals ( ResourceGenerator . CSS_DEBUGPATH ) ) { bundlePrefix += FAKE_BUNDLE_PREFIX ; } if ( ! "" . equals ( jawrConfig . getServletMapping ( ) ) ) { bundlePrefix = PathNormalizer . asPath ( jawrConfig . getServletMapping ( ) + bundlePrefix ) + "/" ; } return bundlePrefix ; }
Returns the bundle prefix
2,734
private Set < String > initExcludedPathList ( Set < String > paths ) { Set < String > toExclude = new HashSet < > ( ) ; if ( null == paths ) return toExclude ; for ( String path : paths ) { path = PathNormalizer . asPath ( path ) ; toExclude . add ( path ) ; } return toExclude ; }
Determine which paths are to be excluded based on a set of path mappings from the configuration .
2,735
protected void addBundlesToMapping ( ) throws DuplicateBundlePathException { Set < String > paths = rsHandler . getResourceNames ( baseDir ) ; for ( String path : paths ) { path = PathNormalizer . joinPaths ( baseDir , path ) ; if ( ! excludedPaths . contains ( path ) && rsHandler . isDirectory ( path ) ) { String bundleKey = path + resourceExtension ; addBundleToMap ( bundleKey , path + "/**" ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Added [" + bundleKey + "] with value [" + path + "/**] to a generated path list" ) ; } } }
Generates the resource bundles mapping expressions .
2,736
public List < String > getSortedResources ( ) { List < String > resources = new ArrayList < > ( ) ; try ( BufferedReader bf = new BufferedReader ( reader ) ) { String res ; while ( ( res = bf . readLine ( ) ) != null ) { String name = PathNormalizer . normalizePath ( res . trim ( ) ) ; for ( String available : availableResources ) { if ( PathNormalizer . normalizePath ( available ) . equals ( name ) ) { if ( name . endsWith ( ".js" ) || name . endsWith ( ".css" ) ) resources . add ( PathNormalizer . joinPaths ( dirName , name ) ) ; else resources . add ( PathNormalizer . joinPaths ( dirName , name + "/" ) ) ; availableResources . remove ( available ) ; break ; } } } } catch ( IOException e ) { throw new BundlingProcessException ( "Unexpected IOException reading sort file" , e ) ; } return resources ; }
Creates a list with the ordered resource names and returns it . If a resource is not in the resources dir it is ignored .
2,737
public static String evalString ( String propertyName , String propertyValue , Tag tag , PageContext pageContext ) throws JspException { return ( String ) ExpressionEvaluatorManager . evaluate ( propertyName , propertyValue , String . class , tag , pageContext ) ; }
Evaluate the string EL expression passed as parameter
2,738
public static Boolean evalBoolean ( String propertyName , String propertyValue , Tag tag , PageContext pageContext ) throws JspException { return ( Boolean ) ExpressionEvaluatorManager . evaluate ( propertyName , propertyValue , Boolean . class , tag , pageContext ) ; }
Evaluate the boolean EL expression passed as parameter
2,739
public List < JoinableResourceBundle > getResourceBundles ( Properties properties ) { PropertiesConfigHelper props = new PropertiesConfigHelper ( properties , resourceType ) ; String fileExtension = "." + resourceType ; List < JoinableResourceBundle > customBundles = new ArrayList < > ( ) ; if ( null != props . getProperty ( PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_NAMES ) ) { StringTokenizer tk = new StringTokenizer ( props . getProperty ( PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_NAMES ) , "," ) ; while ( tk . hasMoreTokens ( ) ) { customBundles . add ( buildJoinableResourceBundle ( props , tk . nextToken ( ) . trim ( ) , fileExtension , rsReaderHandler ) ) ; } } else { Iterator < String > bundleNames = props . getPropertyBundleNameSet ( ) . iterator ( ) ; while ( bundleNames . hasNext ( ) ) { customBundles . add ( buildJoinableResourceBundle ( props , bundleNames . next ( ) , fileExtension , rsReaderHandler ) ) ; } } Iterator < String > bundleNames = props . getPropertyBundleNameSet ( ) . iterator ( ) ; while ( bundleNames . hasNext ( ) ) { String bundleName = ( String ) bundleNames . next ( ) ; List < String > bundleNameDependencies = props . getCustomBundlePropertyAsList ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_DEPENDENCIES ) ; if ( ! bundleNameDependencies . isEmpty ( ) ) { JoinableResourceBundle bundle = getBundleFromName ( bundleName , customBundles ) ; List < JoinableResourceBundle > bundleDependencies = getBundlesFromName ( bundleNameDependencies , customBundles ) ; bundle . setDependencies ( bundleDependencies ) ; } } return customBundles ; }
Returns the list of joinable resource bundle
2,740
private JoinableResourceBundle getBundleFromName ( String bundleName , List < JoinableResourceBundle > bundles ) { JoinableResourceBundle bundle = null ; List < String > names = new ArrayList < > ( ) ; names . add ( bundleName ) ; List < JoinableResourceBundle > result = getBundlesFromName ( names , bundles ) ; if ( ! result . isEmpty ( ) ) { bundle = result . get ( 0 ) ; } return bundle ; }
Returns a bundle using the bundle name from a list of bundles
2,741
private List < JoinableResourceBundle > getBundlesFromName ( List < String > names , List < JoinableResourceBundle > bundles ) { List < JoinableResourceBundle > resultBundles = new ArrayList < > ( ) ; for ( String name : names ) { for ( JoinableResourceBundle bundle : bundles ) { if ( bundle . getName ( ) . equals ( name ) ) { resultBundles . add ( bundle ) ; } } } return resultBundles ; }
Returns a list of bundles using the bundle names from a list of bundles
2,742
private void verifyIfBundleIsModified ( JoinableResourceBundleImpl bundle , List < String > mappings , PropertiesConfigHelper props ) { Map < String , VariantSet > variants = new TreeMap < > ( ) ; for ( String mapping : mappings ) { variants = VariantUtils . concatVariants ( variants , generatorRegistry . getAvailableVariants ( mapping ) ) ; } if ( ! variants . equals ( bundle . getVariants ( ) ) ) { bundle . setVariants ( variants ) ; bundle . setDirty ( true ) ; } else { String bundleName = bundle . getName ( ) ; List < String > fileMappings = props . getCustomBundlePropertyAsList ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_FILEPATH_MAPPINGS ) ; if ( fileMappings != null ) { List < FilePathMapping > bundleFileMappings = bundle . getFilePathMappings ( ) ; if ( bundleFileMappings . size ( ) != fileMappings . size ( ) ) { bundle . setDirty ( true ) ; } else { Set < FilePathMapping > storedFilePathMapping = new HashSet < > ( ) ; for ( String filePathWithTimeStamp : fileMappings ) { String [ ] tmp = filePathWithTimeStamp . split ( LAST_MODIFIED_SEPARATOR ) ; String filePath = tmp [ 0 ] ; long storedLastModified = Long . parseLong ( tmp [ 1 ] ) ; storedFilePathMapping . add ( new FilePathMapping ( bundle , filePath , storedLastModified ) ) ; } Set < FilePathMapping > bundleFilePathMappingSet = new HashSet < > ( bundleFileMappings ) ; if ( ! bundleFilePathMappingSet . equals ( storedFilePathMapping ) ) { bundle . setDirty ( true ) ; } } } fileMappings = props . getCustomBundlePropertyAsList ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_LINKED_FILEPATH_MAPPINGS ) ; for ( String filePathWithTimeStamp : fileMappings ) { int idx = filePathWithTimeStamp . lastIndexOf ( LAST_MODIFIED_SEPARATOR ) ; if ( idx != - 1 ) { String filePath = filePathWithTimeStamp . substring ( 0 , idx ) ; long storedLastModified = Long . parseLong ( filePathWithTimeStamp . substring ( idx + 1 ) ) ; long currentLastModified = rsReaderHandler . getLastModified ( filePath ) ; FilePathMapping fPathMapping = new FilePathMapping ( bundle , filePath , currentLastModified ) ; bundle . getLinkedFilePathMappings ( ) . add ( fPathMapping ) ; if ( storedLastModified != currentLastModified ) { bundle . setDirty ( true ) ; } } } } }
Verify f the bundle has been modified
2,743
private InclusionPattern getInclusionPattern ( PropertiesConfigHelper props , String bundleName ) { boolean isGlobal = Boolean . parseBoolean ( props . getCustomBundleProperty ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_GLOBAL_FLAG , "false" ) ) ; int order = 0 ; if ( isGlobal ) { order = Integer . parseInt ( props . getCustomBundleProperty ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_ORDER , "0" ) ) ; } boolean isDebugOnly = Boolean . parseBoolean ( props . getCustomBundleProperty ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_DEBUGONLY , "false" ) ) ; boolean isDebugNever = Boolean . parseBoolean ( props . getCustomBundleProperty ( bundleName , PropertiesBundleConstant . BUNDLE_FACTORY_CUSTOM_DEBUGNEVER , "false" ) ) ; return new InclusionPattern ( isGlobal , order , DebugInclusion . get ( isDebugOnly , isDebugNever ) ) ; }
Returns the inclusion pattern for a bundle
2,744
protected boolean isBinaryResource ( String resourcePath ) { String extension = FileNameUtils . getExtension ( resourcePath ) ; if ( extension != null ) { extension = extension . toLowerCase ( ) ; } return MIMETypesSupport . getSupportedProperties ( this ) . containsKey ( extension ) ; }
Checks if the resource is an binary resource
2,745
private String addCacheBuster ( String url , BinaryResourcesHandler binaryRsHandler ) throws IOException { if ( binaryRsHandler != null ) { FilePathMappingUtils . buildFilePathMapping ( bundle , url , binaryRsHandler . getRsReaderHandler ( ) ) ; } String newUrl = null ; if ( binaryMapping != null ) { newUrl = binaryMapping . get ( url ) ; if ( newUrl != null ) { return newUrl ; } } if ( binaryRsHandler != null ) { newUrl = binaryRsHandler . getCacheUrl ( url ) ; if ( newUrl != null ) { return newUrl ; } try { newUrl = CheckSumUtils . getCacheBustedUrl ( url , binaryRsHandler . getRsReaderHandler ( ) , binaryRsHandler . getConfig ( ) ) ; } catch ( ResourceNotFoundException e ) { LOGGER . info ( "Impossible to define the checksum for the resource '" + url + "'. " ) ; return url ; } catch ( IOException e ) { LOGGER . info ( "Impossible to define the checksum for the resource '" + url + "'." ) ; return url ; } binaryRsHandler . addMapping ( url , newUrl ) ; } else { newUrl = url ; } binaryMapping . put ( url , newUrl ) ; return newUrl ; }
Adds the cache buster to the CSS image
2,746
protected String getBody ( HttpEntity entity , String enc ) throws IOException { final StringBuilder body = new StringBuilder ( ) ; String buffer = "" ; if ( entity != null ) { final BufferedReader reader = new BufferedReader ( new InputStreamReader ( entity . getContent ( ) , enc ) ) ; while ( ( buffer = reader . readLine ( ) ) != null ) { body . append ( buffer ) ; } reader . close ( ) ; } return body . toString ( ) ; }
Get the body .
2,747
protected Map < String , String > getHeaders ( HttpResponse resp ) { final Map < String , String > headersAndValues = new HashMap < String , String > ( ) ; final Header [ ] httpHeaders = resp . getAllHeaders ( ) ; for ( Header header : httpHeaders ) { headersAndValues . put ( header . getName ( ) , header . getValue ( ) ) ; } return headersAndValues ; }
Get the headers from the response .
2,748
public static String convertToClob ( final String varchar ) { int startIndex = 0 ; int endIndex = Math . min ( startIndex + 4000 , varchar . length ( ) ) ; final StringBuilder clobs = new StringBuilder ( "TO_CLOB('" ) . append ( varchar . substring ( startIndex , endIndex ) ) . append ( "')" ) ; while ( endIndex < varchar . length ( ) ) { startIndex = endIndex ; endIndex = Math . min ( startIndex + 4000 , varchar . length ( ) ) ; clobs . append ( " || TO_CLOB('" ) . append ( varchar . substring ( startIndex , endIndex ) ) . append ( "')" ) ; } return clobs . toString ( ) ; }
Generates the SQL to convert the given string to a CLOB .
2,749
public static String getOracleSrid ( final String srid , final Database database ) { final String oracleSrid ; if ( StringUtils . trimToNull ( srid ) == null ) { oracleSrid = null ; } else if ( EPSG_TO_ORACLE_MAP . containsKey ( srid ) ) { oracleSrid = EPSG_TO_ORACLE_MAP . get ( srid ) ; } else { oracleSrid = loadOracleSrid ( srid , database ) ; EPSG_TO_ORACLE_MAP . put ( srid , oracleSrid ) ; } return oracleSrid ; }
Converts the given EPSG SRID to the corresponding Oracle SRID .
2,750
public static String loadOracleSrid ( final String srid , final Database database ) { final String oracleSrid ; final JdbcConnection jdbcConnection = ( JdbcConnection ) database . getConnection ( ) ; final Connection connection = jdbcConnection . getUnderlyingConnection ( ) ; Statement statement = null ; try { statement = connection . createStatement ( ) ; final ResultSet resultSet = statement . executeQuery ( "SELECT " + EPSG_TO_ORACLE_FUNCTION + "(" + srid + ") FROM dual" ) ; resultSet . next ( ) ; oracleSrid = resultSet . getString ( 1 ) ; } catch ( final SQLException e ) { throw new UnexpectedLiquibaseException ( "Failed to find the Oracle SRID for EPSG:" + srid , e ) ; } finally { try { statement . close ( ) ; } catch ( final SQLException ignore ) { } } return oracleSrid ; }
Queries to the database to convert the given EPSG SRID to the corresponding Oracle SRID .
2,751
protected void dropSpatialIndexIfExists ( final String catalogName , final String schemaName , final String tableName , final Database database , final List < Sql > list ) { final DropSpatialIndexGeneratorGeoDB generator = new DropSpatialIndexGeneratorGeoDB ( ) ; final DropSpatialIndexStatement statement = new DropSpatialIndexStatement ( null , catalogName , schemaName , tableName ) ; list . addAll ( Arrays . asList ( generator . generateSqlIfExists ( statement , database ) ) ) ; }
Adds the SQL statement to drop the spatial index if it is present .
2,752
public ValidationErrors validate ( final DropSpatialIndexStatement statement , final Database database , final SqlGeneratorChain sqlGeneratorChain ) { final ValidationErrors validationErrors = new ValidationErrors ( ) ; validationErrors . checkRequiredField ( "tableName" , statement . getTableName ( ) ) ; return validationErrors ; }
Ensures that the table name is populated .
2,753
public Sql [ ] generateSqlIfExists ( final DropSpatialIndexStatement statement , final Database database ) { final String catalogName = statement . getTableCatalogName ( ) ; final String schemaName = statement . getTableSchemaName ( ) ; final String tableName = statement . getTableName ( ) ; final SpatialIndexExistsPrecondition precondition = new SpatialIndexExistsPrecondition ( ) ; precondition . setCatalogName ( catalogName ) ; precondition . setSchemaName ( schemaName ) ; precondition . setTableName ( tableName ) ; final DatabaseObject example = precondition . getExample ( database , tableName ) ; try { if ( SnapshotGeneratorFactory . getInstance ( ) . has ( example , database ) ) { return generateSql ( statement , database , null ) ; } } catch ( final Exception e ) { throw new UnexpectedLiquibaseException ( e ) ; } return new Sql [ 0 ] ; }
Generates the SQL statement to drop the spatial index if it exists .
2,754
protected String generateCreateIndexSql ( final CreateSpatialIndexStatement statement , final Database database ) { final StringBuilder sql = new StringBuilder ( ) ; sql . append ( "CREATE INDEX " ) ; final String schemaName = statement . getTableSchemaName ( ) ; final String catalogName = statement . getTableCatalogName ( ) ; final String indexName = statement . getIndexName ( ) ; sql . append ( database . escapeIndexName ( catalogName , schemaName , indexName ) ) ; sql . append ( " ON " ) ; final String tableName = statement . getTableName ( ) ; sql . append ( database . escapeTableName ( catalogName , schemaName , tableName ) ) . append ( " (" ) ; final Iterator < String > iterator = Arrays . asList ( statement . getColumns ( ) ) . iterator ( ) ; final String column = iterator . next ( ) ; sql . append ( database . escapeColumnName ( catalogName , statement . getTableSchemaName ( ) , tableName , column ) ) ; sql . append ( ") INDEXTYPE IS mdsys.spatial_index" ) ; final Collection < String > parameters = getParameters ( statement ) ; if ( parameters != null && ! parameters . isEmpty ( ) ) { sql . append ( " PARAMETERS ('" ) ; sql . append ( StringUtils . join ( parameters , " " ) ) ; sql . append ( "')" ) ; } return sql . toString ( ) ; }
Generates the SQL for creating the spatial index .
2,755
protected Collection < String > getParameters ( final CreateSpatialIndexStatement statement ) { final Collection < String > parameters = new ArrayList < String > ( ) ; if ( StringUtils . trimToNull ( statement . getGeometryType ( ) ) != null ) { final String gType = getGtype ( statement . getGeometryType ( ) . trim ( ) ) ; if ( gType != null ) { parameters . add ( "layer_gtype=" + gType ) ; } } if ( StringUtils . trimToNull ( statement . getTablespace ( ) ) != null ) { parameters . add ( "tablespace=" + statement . getTablespace ( ) . trim ( ) ) ; } return parameters ; }
Creates the parameters to the spatial index creation statement .
2,756
@ SuppressWarnings ( "deprecation" ) public static DefaultHttpClient getClientThatAllowAnyHTTPS ( ThreadSafeClientConnManager cm ) { final TrustManager easyTrustManager = new X509TrustManager ( ) { public void checkClientTrusted ( X509Certificate [ ] xcs , String string ) throws CertificateException { } public void checkServerTrusted ( X509Certificate [ ] xcs , String string ) throws CertificateException { } public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } } ; final X509HostnameVerifier easyVerifier = new X509HostnameVerifier ( ) { public boolean verify ( String string , SSLSession ssls ) { return true ; } public void verify ( String string , SSLSocket ssls ) throws IOException { } public void verify ( String string , String [ ] strings , String [ ] strings1 ) throws SSLException { } public void verify ( String string , X509Certificate xc ) throws SSLException { } } ; SSLContext ctx = null ; try { ctx = SSLContext . getInstance ( "TLS" ) ; ctx . init ( null , new TrustManager [ ] { easyTrustManager } , null ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } catch ( KeyManagementException e ) { throw new RuntimeException ( e ) ; } final SSLSocketFactory ssf = new SSLSocketFactory ( ctx ) ; ssf . setHostnameVerifier ( easyVerifier ) ; cm . getSchemeRegistry ( ) . register ( new Scheme ( HTTPS , ssf , HTTPS_PORT ) ) ; return new DefaultHttpClient ( cm ) ; }
Get a HttpClient that accept any HTTP certificate .
2,757
public Set < CrawlerURL > get ( HTMLPageResponse theResponse ) { final String url = theResponse . getUrl ( ) ; Set < CrawlerURL > ahrefs = new HashSet < CrawlerURL > ( ) ; if ( theResponse . getResponseCode ( ) == HttpStatus . SC_OK ) { ahrefs = fetch ( AHREF , ABS_HREF , theResponse . getBody ( ) , url ) ; } return ahrefs ; }
Get all ahref links within this page response .
2,758
protected Options getOptions ( ) { final Options options = super . getOptions ( ) ; final Option urlOption = new Option ( "u" , "the page that is the startpoint of the crawl, examle http://mydomain.com/mypage" ) ; urlOption . setLongOpt ( URL ) ; urlOption . setArgName ( "URL" ) ; urlOption . setRequired ( true ) ; urlOption . setArgs ( 1 ) ; options . addOption ( urlOption ) ; final Option levelOption = new Option ( "l" , "how deep the crawl should be done, default is " + CrawlerConfiguration . DEFAULT_CRAWL_LEVEL + " [optional]" ) ; levelOption . setArgName ( "LEVEL" ) ; levelOption . setLongOpt ( LEVEL ) ; levelOption . setRequired ( false ) ; levelOption . setArgs ( 1 ) ; options . addOption ( levelOption ) ; final Option followOption = new Option ( "p" , "stay on this path when crawling [optional]" ) ; followOption . setArgName ( "PATH" ) ; followOption . setLongOpt ( FOLLOW_PATH ) ; followOption . setRequired ( false ) ; followOption . setArgs ( 1 ) ; options . addOption ( followOption ) ; final Option noFollowOption = new Option ( "np" , "no url:s on this path will be crawled [optional]" ) ; noFollowOption . setArgName ( "NOPATH" ) ; noFollowOption . setLongOpt ( NO_FOLLOW_PATH ) ; noFollowOption . setRequired ( false ) ; noFollowOption . setArgs ( 1 ) ; options . addOption ( noFollowOption ) ; final Option verifyOption = new Option ( "v" , "verify that all links are returning 200, default is set to " + CrawlerConfiguration . DEFAULT_SHOULD_VERIFY_URLS + " [optional]" ) ; verifyOption . setArgName ( "VERIFY" ) ; verifyOption . setLongOpt ( VERIFY ) ; verifyOption . setRequired ( false ) ; verifyOption . setArgs ( 1 ) ; options . addOption ( verifyOption ) ; final Option requestHeadersOption = new Option ( "rh" , "the request headers by the form of header1:value1@header2:value2 [optional]" ) ; requestHeadersOption . setArgName ( "REQUEST-HEADERS" ) ; requestHeadersOption . setLongOpt ( REQUEST_HEADERS ) ; requestHeadersOption . setRequired ( false ) ; requestHeadersOption . setArgs ( 1 ) ; options . addOption ( requestHeadersOption ) ; return options ; }
Get hold of the default options .
2,759
public Sql [ ] generateSql ( final InsertStatement statement , final Database database , final SqlGeneratorChain sqlGeneratorChain ) { for ( final Entry < String , Object > entry : statement . getColumnValues ( ) . entrySet ( ) ) { entry . setValue ( handleColumnValue ( entry . getValue ( ) , database ) ) ; } return super . generateSql ( statement , database , sqlGeneratorChain ) ; }
Find any fields that look like WKT or EWKT and replace them with the database - specific value .
2,760
public ValidationErrors validate ( final CreateSpatialIndexStatement statement , final Database database , final SqlGeneratorChain sqlGeneratorChain ) { final ValidationErrors validationErrors = new ValidationErrors ( ) ; validationErrors . checkRequiredField ( "tableName" , statement . getTableName ( ) ) ; validationErrors . checkRequiredField ( "columns" , statement . getColumns ( ) ) ; return validationErrors ; }
Ensures that the table name and columns are populated .
2,761
public static String convertToFunction ( final String wkt , final String srid , final Database database , final WktInsertOrUpdateGenerator generator ) { if ( wkt == null || wkt . equals ( "" ) ) { throw new IllegalArgumentException ( "The Well-Known Text cannot be null or empty" ) ; } if ( generator == null ) { throw new IllegalArgumentException ( "The generator cannot be null or empty" ) ; } final String geomFromTextFunction = generator . getGeomFromWktFunction ( ) ; String function = geomFromTextFunction + "('" + wkt + "'" ; if ( srid != null && ! srid . equals ( "" ) ) { function += ", " + srid ; } else if ( generator . isSridRequiredInFunction ( database ) ) { throw new IllegalArgumentException ( "An SRID was not provided with '" + wkt + "' but is required in call to '" + geomFromTextFunction + "'" ) ; } function += ")" ; return function ; }
Converts the given Well - Known Text and SRID to the appropriate function call for the database .
2,762
public String getGeometryType ( ) { String geometryType = null ; if ( getParameters ( ) . length > 0 && getParameters ( ) [ 0 ] != null ) { geometryType = getParameters ( ) [ 0 ] . toString ( ) ; } return geometryType ; }
Returns the value geometry type parameter .
2,763
public Integer getSRID ( ) { Integer srid = null ; if ( getParameters ( ) . length > 1 && getParameters ( ) [ 1 ] != null ) { srid = Integer . valueOf ( getParameters ( ) [ 1 ] . toString ( ) ) ; } return srid ; }
Returns the value SRID parameter .
2,764
public HttpClient get ( ) { final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager ( ) ; cm . setMaxTotal ( nrOfThreads ) ; cm . setDefaultMaxPerRoute ( maxToRoute ) ; final DefaultHttpClient client = HTTPSFaker . getClientThatAllowAnyHTTPS ( cm ) ; client . getParams ( ) . setParameter ( "http.socket.timeout" , socketTimeout ) ; client . getParams ( ) . setParameter ( "http.connection.timeout" , connectionTimeout ) ; client . addRequestInterceptor ( new RequestAcceptEncoding ( ) ) ; client . addResponseInterceptor ( new ResponseContentEncoding ( ) ) ; CookieSpecFactory csf = new CookieSpecFactory ( ) { public CookieSpec newInstance ( HttpParams params ) { return new BestMatchSpecWithURLErrorLog ( ) ; } } ; client . getCookieSpecs ( ) . register ( "bestmatchwithurl" , csf ) ; client . getParams ( ) . setParameter ( ClientPNames . COOKIE_POLICY , "bestmatchwithurl" ) ; if ( ! "" . equals ( proxy ) ) { StringTokenizer token = new StringTokenizer ( proxy , ":" ) ; if ( token . countTokens ( ) == 3 ) { String proxyProtocol = token . nextToken ( ) ; String proxyHost = token . nextToken ( ) ; int proxyPort = Integer . parseInt ( token . nextToken ( ) ) ; HttpHost proxy = new HttpHost ( proxyHost , proxyPort , proxyProtocol ) ; client . getParams ( ) . setParameter ( ConnRoutePNames . DEFAULT_PROXY , proxy ) ; } else System . err . println ( "Invalid proxy configuration: " + proxy ) ; } if ( auths . size ( ) > 0 ) { for ( Auth authObject : auths ) { client . getCredentialsProvider ( ) . setCredentials ( new AuthScope ( authObject . getScope ( ) , authObject . getPort ( ) ) , new UsernamePasswordCredentials ( authObject . getUserName ( ) , authObject . getPassword ( ) ) ) ; } } return client ; }
Get the client .
2,765
public Map < String , String > createHeadersFromString ( String headersAndValues ) { if ( headersAndValues == null || headersAndValues . isEmpty ( ) ) return Collections . emptyMap ( ) ; final StringTokenizer token = new StringTokenizer ( headersAndValues , "@" ) ; final Map < String , String > theHeaders = new HashMap < String , String > ( token . countTokens ( ) ) ; while ( token . hasMoreTokens ( ) ) { final String headerAndValue = token . nextToken ( ) ; if ( ! headerAndValue . contains ( ":" ) ) throw new IllegalArgumentException ( "Request headers wrongly configured, missing separator :" + headersAndValues ) ; final String header = headerAndValue . substring ( 0 , headerAndValue . indexOf ( ":" ) ) ; final String value = headerAndValue . substring ( headerAndValue . indexOf ( ":" ) + 1 , headerAndValue . length ( ) ) ; theHeaders . put ( header , value ) ; } return theHeaders ; }
Create headers from a string .
2,766
public Set < Auth > createAuthsFromString ( String authInfo ) { if ( "" . equals ( authInfo ) || authInfo == null ) return Collections . emptySet ( ) ; String [ ] parts = authInfo . split ( "," ) ; final Set < Auth > auths = new HashSet < Auth > ( ) ; try { for ( String auth : parts ) { StringTokenizer tokenizer = new StringTokenizer ( auth , ":" ) ; while ( tokenizer . hasMoreTokens ( ) ) { auths . add ( new Auth ( tokenizer . nextToken ( ) , tokenizer . nextToken ( ) , tokenizer . nextToken ( ) , tokenizer . nextToken ( ) ) ) ; } } return auths ; } catch ( NoSuchElementException e ) { final StringBuilder b = new StringBuilder ( ) ; for ( String auth : parts ) { b . append ( auth ) ; } throw new IllegalArgumentException ( "Auth configuration is configured wrongly:" + b . toString ( ) , e ) ; } }
Create a auth object from a String looking like .
2,767
protected String getHatboxTableName ( ) { final String tableName ; if ( ! StringUtils . hasUpperCase ( getTableName ( ) ) ) { tableName = getTableName ( ) + "_hatbox" ; } else { tableName = getTableName ( ) + "_HATBOX" ; } return tableName ; }
Generates the table name containing the Hatbox index .
2,768
public DatabaseObject getExample ( final Database database , final String tableName ) { final Schema schema = new Schema ( getCatalogName ( ) , getSchemaName ( ) ) ; final DatabaseObject example ; if ( database instanceof DerbyDatabase || database instanceof H2Database ) { final String correctedTableName = database . correctObjectName ( getHatboxTableName ( ) , Table . class ) ; example = new Table ( ) . setName ( correctedTableName ) . setSchema ( schema ) ; } else { example = getIndexExample ( database , schema , tableName ) ; } return example ; }
Creates an example of the database object for which to check .
2,769
private static TrustManager [ ] getNonValidatingTrustManagers ( String [ ] acceptedIssuers ) { X509TrustManager x509TrustManager = new CustomX509TrustManager ( acceptedIssuers ) ; return new TrustManager [ ] { x509TrustManager } ; }
we want to allow self - signed certificates .
2,770
public String convertToFunction ( final String wkt , final String srid , final Database database ) { final String oracleWkt = OracleSpatialUtils . getOracleWkt ( wkt ) ; final String oracleSrid = OracleSpatialUtils . getOracleSrid ( srid , database ) ; return super . convertToFunction ( oracleWkt , oracleSrid , database ) ; }
Handles the Well - Known Text and SRID for Oracle .
2,771
public CrawlerResult getUrls ( CrawlerConfiguration configuration ) { final Map < String , String > requestHeaders = configuration . getRequestHeadersMap ( ) ; final HTMLPageResponse resp = verifyInput ( configuration . getStartUrl ( ) , configuration . getOnlyOnPath ( ) , requestHeaders ) ; int level = 0 ; final Set < CrawlerURL > allUrls = new LinkedHashSet < CrawlerURL > ( ) ; final Set < HTMLPageResponse > verifiedUrls = new LinkedHashSet < HTMLPageResponse > ( ) ; final Set < HTMLPageResponse > nonWorkingResponses = new LinkedHashSet < HTMLPageResponse > ( ) ; verifiedUrls . add ( resp ) ; final String host = resp . getPageUrl ( ) . getHost ( ) ; if ( configuration . getMaxLevels ( ) > 0 ) { Set < CrawlerURL > nextToFetch = new LinkedHashSet < CrawlerURL > ( ) ; nextToFetch . add ( resp . getPageUrl ( ) ) ; while ( level < configuration . getMaxLevels ( ) ) { final Map < Future < HTMLPageResponse > , CrawlerURL > futures = new HashMap < Future < HTMLPageResponse > , CrawlerURL > ( nextToFetch . size ( ) ) ; for ( CrawlerURL testURL : nextToFetch ) { futures . put ( service . submit ( new HTMLPageResponseCallable ( testURL , responseFetcher , true , requestHeaders , false ) ) , testURL ) ; } nextToFetch = fetchNextLevelLinks ( futures , allUrls , nonWorkingResponses , verifiedUrls , host , configuration . getOnlyOnPath ( ) , configuration . getNotOnPath ( ) ) ; level ++ ; } } else { allUrls . add ( resp . getPageUrl ( ) ) ; } if ( configuration . isVerifyUrls ( ) ) verifyUrls ( allUrls , verifiedUrls , nonWorkingResponses , requestHeaders ) ; LinkedHashSet < CrawlerURL > workingUrls = new LinkedHashSet < CrawlerURL > ( ) ; for ( HTMLPageResponse workingResponses : verifiedUrls ) { workingUrls . add ( workingResponses . getPageUrl ( ) ) ; } if ( workingUrls . size ( ) >= 1 ) { List < CrawlerURL > list = new ArrayList < CrawlerURL > ( workingUrls ) ; list . add ( 0 , new CrawlerURL ( configuration . getStartUrl ( ) ) ) ; list . remove ( 1 ) ; workingUrls . clear ( ) ; workingUrls . addAll ( list ) ; } return new CrawlerResult ( configuration . getStartUrl ( ) , configuration . isVerifyUrls ( ) ? workingUrls : allUrls , verifiedUrls , nonWorkingResponses ) ; }
Get the urls .
2,772
protected Set < CrawlerURL > fetchNextLevelLinks ( Map < Future < HTMLPageResponse > , CrawlerURL > responses , Set < CrawlerURL > allUrls , Set < HTMLPageResponse > nonWorkingUrls , Set < HTMLPageResponse > verifiedUrls , String host , String onlyOnPath , String notOnPath ) { final Set < CrawlerURL > nextLevel = new LinkedHashSet < CrawlerURL > ( ) ; final Iterator < Entry < Future < HTMLPageResponse > , CrawlerURL > > it = responses . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { final Entry < Future < HTMLPageResponse > , CrawlerURL > entry = it . next ( ) ; try { final HTMLPageResponse response = entry . getKey ( ) . get ( ) ; if ( HttpStatus . SC_OK == response . getResponseCode ( ) && response . getResponseType ( ) . indexOf ( "html" ) > 0 ) { verifiedUrls . add ( response ) ; final Set < CrawlerURL > allLinks = parser . get ( response ) ; for ( CrawlerURL link : allLinks ) { if ( host . equals ( link . getHost ( ) ) && link . getUrl ( ) . contains ( onlyOnPath ) && ( notOnPath . equals ( "" ) ? true : ( ! link . getUrl ( ) . contains ( notOnPath ) ) ) ) { if ( ! allUrls . contains ( link ) ) { nextLevel . add ( link ) ; allUrls . add ( link ) ; } } } } else if ( HttpStatus . SC_OK != response . getResponseCode ( ) || StatusCode . SC_SERVER_REDIRECT_TO_NEW_DOMAIN . getCode ( ) == response . getResponseCode ( ) ) { allUrls . remove ( entry . getValue ( ) ) ; nonWorkingUrls . add ( response ) ; } else { allUrls . remove ( entry . getValue ( ) ) ; } } catch ( InterruptedException e ) { nonWorkingUrls . add ( new HTMLPageResponse ( entry . getValue ( ) , StatusCode . SC_SERVER_RESPONSE_UNKNOWN . getCode ( ) , Collections . < String , String > emptyMap ( ) , "" , "" , 0 , "" , - 1 ) ) ; } catch ( ExecutionException e ) { nonWorkingUrls . add ( new HTMLPageResponse ( entry . getValue ( ) , StatusCode . SC_SERVER_RESPONSE_UNKNOWN . getCode ( ) , Collections . < String , String > emptyMap ( ) , "" , "" , 0 , "" , - 1 ) ) ; } } return nextLevel ; }
Fetch links to the next level of the crawl .
2,773
private void verifyUrls ( Set < CrawlerURL > allUrls , Set < HTMLPageResponse > verifiedUrls , Set < HTMLPageResponse > nonWorkingUrls , Map < String , String > requestHeaders ) { Set < CrawlerURL > urlsThatNeedsVerification = new LinkedHashSet < CrawlerURL > ( allUrls ) ; urlsThatNeedsVerification . removeAll ( verifiedUrls ) ; final Set < Callable < HTMLPageResponse > > tasks = new HashSet < Callable < HTMLPageResponse > > ( urlsThatNeedsVerification . size ( ) ) ; for ( CrawlerURL testURL : urlsThatNeedsVerification ) { tasks . add ( new HTMLPageResponseCallable ( testURL , responseFetcher , true , requestHeaders , false ) ) ; } try { List < Future < HTMLPageResponse > > responses = service . invokeAll ( tasks ) ; for ( Future < HTMLPageResponse > future : responses ) { if ( ! future . isCancelled ( ) ) { HTMLPageResponse response = future . get ( ) ; if ( response . getResponseCode ( ) == HttpStatus . SC_OK && response . getResponseType ( ) . indexOf ( "html" ) > 0 ) { urlsThatNeedsVerification . remove ( response . getPageUrl ( ) ) ; verifiedUrls . add ( response ) ; } else if ( response . getResponseCode ( ) == HttpStatus . SC_OK ) { urlsThatNeedsVerification . remove ( response . getPageUrl ( ) ) ; } else { nonWorkingUrls . add ( response ) ; } } } } catch ( InterruptedException e1 ) { e1 . printStackTrace ( ) ; } catch ( ExecutionException e ) { e . printStackTrace ( ) ; } }
Verify that all urls in allUrls returns 200 . If not they will be removed from that set and instead added to the nonworking list .
2,774
public void setAdditionalHeaders ( Map < String , String > additionalHeaders ) { Map < String , String > newMap = new HashMap < > ( ) ; for ( Entry < String , String > e : additionalHeaders . entrySet ( ) ) { boolean found = false ; for ( String restrictedHeaderField : RESTRICTED_HTTP_HEADERS ) { if ( e . getKey ( ) . equalsIgnoreCase ( restrictedHeaderField ) ) { found = true ; break ; } } if ( ! found ) { newMap . put ( e . getKey ( ) , e . getValue ( ) ) ; } } this . additionalHeaders = newMap ; }
Sets additional overall HTTP headers to add to the upload POST request . There s rarely a need to use this method .
2,775
protected void configure ( ) { super . configure ( ) ; bind ( Crawler . class ) . to ( DefaultCrawler . class ) ; bind ( ExecutorService . class ) . toProvider ( ExecutorServiceProvider . class ) ; bind ( HTMLPageResponseFetcher . class ) . to ( HTTPClientResponseFetcher . class ) ; bind ( HttpClient . class ) . toProvider ( HttpClientProvider . class ) ; bind ( PageURLParser . class ) . to ( AhrefPageURLParser . class ) ; bind ( AssetsParser . class ) . to ( DefaultAssetsParser . class ) ; bind ( AssetsVerifier . class ) . to ( DefaultAssetsVerifier . class ) ; bind ( AssetFetcher . class ) . to ( HTTPClientAssetFetcher . class ) ; }
Bind the classes .
2,776
private static boolean byteSizeIsKnown ( Collection < ? extends UploadItem > uploadItems ) { for ( UploadItem uploadItem : uploadItems ) { if ( uploadItem . getSizeInBytes ( ) == - 1 ) { return false ; } } return true ; }
Determines if there are upload items where the size is unknown in advance . This means we cannot predict the total upload size .
2,777
public static boolean isWatchConnected ( final Context context ) { Cursor c = null ; try { c = queryProvider ( context ) ; if ( c == null || ! c . moveToNext ( ) ) { return false ; } return c . getInt ( KIT_STATE_COLUMN_CONNECTED ) == 1 ; } finally { if ( c != null ) { c . close ( ) ; } } }
Synchronously query the Pebble application to see if an active Bluetooth connection to a watch currently exists .
2,778
public static boolean areAppMessagesSupported ( final Context context ) { Cursor c = null ; try { c = queryProvider ( context ) ; if ( c == null || ! c . moveToNext ( ) ) { return false ; } return c . getInt ( KIT_STATE_COLUMN_APPMSG_SUPPORT ) == 1 ; } finally { if ( c != null ) { c . close ( ) ; } } }
Synchronously query the Pebble application to see if the connected watch is running a firmware version that supports PebbleKit messages .
2,779
public static FirmwareVersionInfo getWatchFWVersion ( final Context context ) { Cursor c = null ; try { c = queryProvider ( context ) ; if ( c == null || ! c . moveToNext ( ) ) { return null ; } int majorVersion = c . getInt ( KIT_STATE_COLUMN_VERSION_MAJOR ) ; int minorVersion = c . getInt ( KIT_STATE_COLUMN_VERSION_MINOR ) ; int pointVersion = c . getInt ( KIT_STATE_COLUMN_VERSION_POINT ) ; String versionTag = c . getString ( KIT_STATE_COLUMN_VERSION_TAG ) ; return new FirmwareVersionInfo ( majorVersion , minorVersion , pointVersion , versionTag ) ; } finally { if ( c != null ) { c . close ( ) ; } } }
Get the version information of the firmware running on a connected watch .
2,780
public static boolean isDataLoggingSupported ( final Context context ) { Cursor c = null ; try { c = queryProvider ( context ) ; if ( c == null || ! c . moveToNext ( ) ) { return false ; } return c . getInt ( KIT_STATE_COLUMN_DATALOGGING_SUPPORT ) == 1 ; } finally { if ( c != null ) { c . close ( ) ; } } }
Synchronously query the Pebble application to see if the connected watch is running a firmware version that supports PebbleKit data logging .
2,781
public static void startAppOnPebble ( final Context context , final UUID watchappUuid ) throws IllegalArgumentException { if ( watchappUuid == null ) { throw new IllegalArgumentException ( "uuid cannot be null" ) ; } final Intent startAppIntent = new Intent ( INTENT_APP_START ) ; startAppIntent . putExtra ( APP_UUID , watchappUuid ) ; context . sendBroadcast ( startAppIntent ) ; }
Send a message to the connected Pebble to launch an application identified by a UUID . If another application is currently running it will be terminated and the new application will be brought to the foreground .
2,782
public static void closeAppOnPebble ( final Context context , final UUID watchappUuid ) throws IllegalArgumentException { if ( watchappUuid == null ) { throw new IllegalArgumentException ( "uuid cannot be null" ) ; } final Intent stopAppIntent = new Intent ( INTENT_APP_STOP ) ; stopAppIntent . putExtra ( APP_UUID , watchappUuid ) ; context . sendBroadcast ( stopAppIntent ) ; }
Send a message to the connected Pebble to close an application identified by a UUID . If this application is not currently running the message is ignored .
2,783
public static void sendDataToPebble ( final Context context , final UUID watchappUuid , final PebbleDictionary data ) throws IllegalArgumentException { sendDataToPebbleWithTransactionId ( context , watchappUuid , data , - 1 ) ; }
Send one - or - more key - value pairs to the watch - app identified by the provided UUID . This is the primary method for sending data from the phone to a connected Pebble .
2,784
public static void sendDataToPebbleWithTransactionId ( final Context context , final UUID watchappUuid , final PebbleDictionary data , final int transactionId ) throws IllegalArgumentException { if ( watchappUuid == null ) { throw new IllegalArgumentException ( "uuid cannot be null" ) ; } if ( data == null ) { throw new IllegalArgumentException ( "data cannot be null" ) ; } if ( data . size ( ) == 0 ) { return ; } final Intent sendDataIntent = new Intent ( INTENT_APP_SEND ) ; sendDataIntent . putExtra ( APP_UUID , watchappUuid ) ; sendDataIntent . putExtra ( TRANSACTION_ID , transactionId ) ; sendDataIntent . putExtra ( MSG_DATA , data . toJsonString ( ) ) ; context . sendBroadcast ( sendDataIntent ) ; }
Send one - or - more key - value pairs to the watch - app identified by the provided UUID .
2,785
public static BroadcastReceiver registerPebbleConnectedReceiver ( final Context context , final BroadcastReceiver receiver ) { return registerBroadcastReceiverInternal ( context , INTENT_PEBBLE_CONNECTED , receiver ) ; }
A convenience function to assist in programatically registering a broadcast receiver for the CONNECTED intent .
2,786
public static BroadcastReceiver registerPebbleDisconnectedReceiver ( final Context context , final BroadcastReceiver receiver ) { return registerBroadcastReceiverInternal ( context , INTENT_PEBBLE_DISCONNECTED , receiver ) ; }
A convenience function to assist in programatically registering a broadcast receiver for the DISCONNECTED intent .
2,787
public static BroadcastReceiver registerReceivedDataHandler ( final Context context , final PebbleDataReceiver receiver ) { return registerBroadcastReceiverInternal ( context , INTENT_APP_RECEIVE , receiver ) ; }
A convenience function to assist in programatically registering a broadcast receiver for the RECEIVE intent .
2,788
public static BroadcastReceiver registerReceivedAckHandler ( final Context context , final PebbleAckReceiver receiver ) { return registerBroadcastReceiverInternal ( context , INTENT_APP_RECEIVE_ACK , receiver ) ; }
A convenience function to assist in programatically registering a broadcast receiver for the RECEIVE_ACK intent .
2,789
public static BroadcastReceiver registerReceivedNackHandler ( final Context context , final PebbleNackReceiver receiver ) { return registerBroadcastReceiverInternal ( context , INTENT_APP_RECEIVE_NACK , receiver ) ; }
A convenience function to assist in programatically registering a broadcast receiver for the RECEIVE_NACK intent .
2,790
private static BroadcastReceiver registerBroadcastReceiverInternal ( final Context context , final String action , final BroadcastReceiver receiver ) { if ( receiver == null ) { return null ; } IntentFilter filter = new IntentFilter ( action ) ; context . registerReceiver ( receiver , filter ) ; return receiver ; }
Register broadcast receiver internal .
2,791
public static BroadcastReceiver registerDataLogReceiver ( final Context context , final PebbleDataLogReceiver receiver ) { IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( INTENT_DL_RECEIVE_DATA ) ; filter . addAction ( INTENT_DL_FINISH_SESSION ) ; context . registerReceiver ( receiver , filter ) ; return receiver ; }
A convenience function to assist in programatically registering a broadcast receiver for the DATA_AVAILABLE intent .
2,792
public static void requestDataLogsForApp ( final Context context , final UUID appUuid ) { final Intent requestIntent = new Intent ( INTENT_DL_REQUEST_DATA ) ; requestIntent . putExtra ( APP_UUID , appUuid ) ; context . sendBroadcast ( requestIntent ) ; }
A convenience function to emit an intent to pebble . apk to request the data logs for a particular app . If data is available pebble . apk will advertise the data via INTENT_DL_RECEIVE_DATA intents .
2,793
private static Cursor queryProvider ( final Context context ) { Cursor c = context . getContentResolver ( ) . query ( Constants . URI_CONTENT_BASALT , null , null , null , null ) ; if ( c != null ) { if ( c . moveToFirst ( ) ) { if ( c . getInt ( KIT_STATE_COLUMN_CONNECTED ) == 1 ) { c . moveToPrevious ( ) ; return c ; } } c . close ( ) ; } c = context . getContentResolver ( ) . query ( Constants . URI_CONTENT_PRIMARY , null , null , null , null ) ; return c ; }
Query the Pebble ContentProvider - utility method for various PebbleKit helper methods
2,794
private int getPerPage ( Context context ) { return ( context . getResources ( ) . getDisplayMetrics ( ) . heightPixels / context . getResources ( ) . getDimensionPixelSize ( R . dimen . repo_item_height ) ) + 3 ; }
Get items to load per page onScroll .
2,795
public static GitHub getClient ( ) { RestAdapter restAdapter = new RestAdapter . Builder ( ) . setEndpoint ( API_URL ) . setLogLevel ( RestAdapter . LogLevel . BASIC ) . build ( ) ; return restAdapter . create ( GitHub . class ) ; }
Get github client .
2,796
public void addBytes ( int key , byte [ ] bytes ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . BYTES , PebbleTuple . Width . NONE , bytes ) ; addTuple ( t ) ; }
Associate the specified byte array with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .
2,797
public void addString ( int key , String value ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . STRING , PebbleTuple . Width . NONE , value ) ; addTuple ( t ) ; }
Associate the specified String with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .
2,798
public void addInt8 ( final int key , final byte b ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . INT , PebbleTuple . Width . BYTE , b ) ; addTuple ( t ) ; }
Associate the specified signed byte with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .
2,799
public void addUint8 ( final int key , final byte b ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . UINT , PebbleTuple . Width . BYTE , b ) ; addTuple ( t ) ; }
Associate the specified unsigned byte with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .