idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
18,100 | public static Properties loadProperties ( URL url ) { if ( null == url ) { return new Properties ( ) ; } return loadProperties ( inputStream ( url ) ) ; } | Load properties from a URL | 38 | 5 |
18,101 | @ Deprecated public static void writeContent ( CharSequence content , File file , String encoding ) { write ( content , file , encoding ) ; } | Write string content to a file with encoding specified . | 31 | 10 |
18,102 | public static void write ( CharSequence content , File file , String encoding ) { OutputStream os = null ; try { os = new FileOutputStream ( file ) ; PrintWriter printWriter = new PrintWriter ( new OutputStreamWriter ( os , encoding ) ) ; printWriter . print ( content ) ; printWriter . flush ( ) ; os . flush ( ) ; } catch ( IOException e ) { throw E . unexpected ( e ) ; } finally { close ( os ) ; } } | Write String content to a file with encoding specified | 102 | 9 |
18,103 | public static void write ( CharSequence content , Writer writer , boolean closeOs ) { try { writer . write ( content . toString ( ) ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { if ( closeOs ) { close ( writer ) ; } } } | Write content into a writer . | 66 | 6 |
18,104 | public static int copy ( InputStream is , OutputStream os , boolean closeOs ) { if ( closeOs ) { return write ( is ) . ensureCloseSink ( ) . to ( os ) ; } else { return write ( is ) . to ( os ) ; } } | Copy an stream to another one . It close the input stream anyway . | 58 | 14 |
18,105 | public static int write ( InputStream is , File f ) { try { return copy ( is , new BufferedOutputStream ( new FileOutputStream ( f ) ) ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } } | Read from inputstream and write into file . | 57 | 9 |
18,106 | public static int copy ( Reader reader , Writer writer , boolean closeWriter ) { if ( closeWriter ) { return write ( reader ) . ensureCloseSink ( ) . to ( writer ) ; } else { return write ( reader ) . to ( writer ) ; } } | Copy from a Reader into a Writer . | 56 | 8 |
18,107 | public static void write ( byte b , OutputStream os ) { try { os . write ( b ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } } | Write a byte into outputstream . | 41 | 7 |
18,108 | public static void write ( byte [ ] data , File file ) { try { write ( new ByteArrayInputStream ( data ) , new BufferedOutputStream ( new FileOutputStream ( file ) ) ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } } | Write binary data to a file | 64 | 6 |
18,109 | public static void write ( byte [ ] data , OutputStream os , boolean closeSink ) { try { os . write ( data ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { if ( closeSink ) { close ( os ) ; } } } | Write binary data to an outputstream . | 64 | 8 |
18,110 | public static void copyDirectory ( File source , File target ) { if ( source . isDirectory ( ) ) { if ( ! target . exists ( ) ) { target . mkdir ( ) ; } for ( String child : source . list ( ) ) { copyDirectory ( new File ( source , child ) , new File ( target , child ) ) ; } } else { try { write ( new FileInputStream ( source ) , new FileOutputStream ( target ) ) ; } catch ( IOException e ) { if ( target . isDirectory ( ) ) { if ( ! target . exists ( ) ) { if ( ! target . mkdirs ( ) ) { throw E . ioException ( "cannot copy [%s] to [%s]" , source , target ) ; } } target = new File ( target , source . getName ( ) ) ; } else { File targetFolder = target . getParentFile ( ) ; if ( ! targetFolder . exists ( ) ) { if ( ! targetFolder . mkdirs ( ) ) { throw E . ioException ( "cannot copy [%s] to [%s]" , source , target ) ; } } } try { write ( new FileInputStream ( source ) , new FileOutputStream ( target ) ) ; } catch ( IOException e0 ) { throw E . ioException ( e0 ) ; } } } } | If target does not exist it will be created . | 291 | 10 |
18,111 | public static ISObject zip ( ISObject ... objects ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ZipOutputStream zos = new ZipOutputStream ( baos ) ; try { for ( ISObject obj : objects ) { ZipEntry entry = new ZipEntry ( obj . getAttribute ( SObject . ATTR_FILE_NAME ) ) ; InputStream is = obj . asInputStream ( ) ; zos . putNextEntry ( entry ) ; copy ( is , zos , false ) ; zos . closeEntry ( ) ; } } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { close ( zos ) ; } return SObject . of ( Codec . encodeUrl ( S . random ( ) ) , baos . toByteArray ( ) ) ; } | Zip a list of sobject into a single sobject . | 175 | 12 |
18,112 | public static File zip ( File ... files ) { try { File temp = File . createTempFile ( "osgl" , ".zip" ) ; zipInto ( temp , files ) ; return temp ; } catch ( IOException e ) { throw E . ioException ( e ) ; } } | Zip a list of files into a single file . The name of the zip file is randomly picked up in the temp dir . | 62 | 25 |
18,113 | public static void zipInto ( File target , File ... files ) { ZipOutputStream zos = null ; try { zos = new ZipOutputStream ( new BufferedOutputStream ( new FileOutputStream ( target ) ) ) ; byte [ ] buffer = new byte [ 128 ] ; for ( File f : files ) { ZipEntry entry = new ZipEntry ( f . getName ( ) ) ; InputStream is = new BufferedInputStream ( new FileInputStream ( f ) ) ; zos . putNextEntry ( entry ) ; int read = 0 ; while ( ( read = is . read ( buffer ) ) != - 1 ) { zos . write ( buffer , 0 , read ) ; } zos . closeEntry ( ) ; IO . close ( is ) ; } } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { IO . close ( zos ) ; } } | Zip a list of files into specified target file . | 194 | 10 |
18,114 | public static < T > T decode ( String string , Class < T > targetType ) { Type type = typeOf ( targetType ) ; return type . decode ( string , targetType ) ; } | Decode a object instance from a string with given target object type | 41 | 13 |
18,115 | public static String encode ( Object o ) { Type type = typeOf ( o ) ; return type . encode ( o ) ; } | Encode a object into a String | 27 | 7 |
18,116 | public int lastIndexOf ( java . util . List < Character > list ) { return lastIndexOf ( ( CharSequence ) FastStr . of ( list ) ) ; } | Returns the index within this str of the last occurrence of the specified character list | 37 | 15 |
18,117 | public static void addGlobalMappingFilters ( String filterSpec , String ... filterSpecs ) { addGlobalMappingFilter ( filterSpec ) ; for ( String s : filterSpecs ) { addGlobalMappingFilter ( s ) ; } } | Register global mapping filters . | 52 | 5 |
18,118 | public static void addGlobalMappingFilter ( String filterSpec ) { List < String > list = S . fastSplit ( filterSpec , "," ) ; for ( String s : list ) { if ( S . blank ( s ) ) { continue ; } addSingleGlobalMappingFilter ( s . trim ( ) ) ; } } | Register a global mapping filter . Unlike normal mapping filter global mapping filter spec | 69 | 14 |
18,119 | public static FastStr of ( char [ ] ca ) { if ( ca . length == 0 ) return EMPTY_STR ; char [ ] newArray = new char [ ca . length ] ; System . arraycopy ( ca , 0 , newArray , 0 , ca . length ) ; return new FastStr ( ca ) ; } | Construct a FastStr from a char array | 68 | 8 |
18,120 | public static FastStr of ( CharSequence cs ) { if ( cs instanceof FastStr ) { return ( FastStr ) cs ; } return of ( cs . toString ( ) ) ; } | Construct a FastStr from a CharSequence | 41 | 9 |
18,121 | public static FastStr of ( String s ) { int sz = s . length ( ) ; if ( sz == 0 ) return EMPTY_STR ; char [ ] buf = s . toCharArray ( ) ; return new FastStr ( buf , 0 , sz ) ; } | Construct a FastStr from a String | 60 | 7 |
18,122 | public static FastStr of ( StringBuilder sb ) { int sz = sb . length ( ) ; if ( 0 == sz ) return EMPTY_STR ; char [ ] buf = new char [ sz ] ; for ( int i = 0 ; i < sz ; ++ i ) { buf [ i ] = sb . charAt ( i ) ; } return new FastStr ( buf , 0 , sz ) ; } | Construct a FastStr from a StringBuilder | 93 | 8 |
18,123 | public static FastStr of ( Iterable < Character > itr ) { StringBuilder sb = new StringBuilder ( ) ; for ( Character c : itr ) { sb . append ( c ) ; } return of ( sb ) ; } | Construct a FastStr instance from an iterable of characters | 52 | 11 |
18,124 | public static FastStr of ( Collection < Character > col ) { int sz = col . size ( ) ; if ( 0 == sz ) return EMPTY_STR ; char [ ] buf = new char [ sz ] ; Iterator < Character > itr = col . iterator ( ) ; int i = 0 ; while ( itr . hasNext ( ) ) { buf [ i ++ ] = itr . next ( ) ; } return new FastStr ( buf , 0 , sz ) ; } | Construct a FastStr instance from a collection of characters | 106 | 10 |
18,125 | public static FastStr of ( Iterator < Character > itr ) { StringBuilder sb = new StringBuilder ( ) ; while ( itr . hasNext ( ) ) { sb . append ( itr . next ( ) ) ; } return of ( sb ) ; } | Construct a FastStr instance from an iterator of characters | 59 | 10 |
18,126 | public static FastStr unsafeOf ( String s ) { int sz = s . length ( ) ; if ( sz == 0 ) return EMPTY_STR ; char [ ] buf = bufOf ( s ) ; return new FastStr ( buf , 0 , sz ) ; } | Construct a FastStr instance from a String instance . The FastStr instance will share the char array buf with the String instance | 59 | 24 |
18,127 | @ SuppressWarnings ( "unused" ) public static FastStr unsafeOf ( char [ ] buf ) { E . NPE ( buf ) ; return new FastStr ( buf , 0 , buf . length ) ; } | Construct a FastStr instance from char array without array copying | 48 | 11 |
18,128 | public static FastStr unsafeOf ( char [ ] buf , int start , int end ) { E . NPE ( buf ) ; E . illegalArgumentIf ( start < 0 || end > buf . length ) ; if ( end < start ) return EMPTY_STR ; return new FastStr ( buf , start , end ) ; } | Construct a FastStr instance from char array from the start position finished at end position without copying the array . This method might use the array directly instead of copying elements from the array . Thus it is extremely important that the array buf passed in will NOT be updated outside the FastStr instance . | 70 | 57 |
18,129 | public StringValueResolver < T > attributes ( Map < String , Object > attributes ) { this . attributes . putAll ( attributes ) ; return this ; } | Set attributes to this resolver | 33 | 6 |
18,130 | public static SObject of ( String key , File file ) { if ( file . canRead ( ) && file . isFile ( ) ) { SObject sobj = new FileSObject ( key , file ) ; String fileName = file . getName ( ) ; sobj . setAttribute ( ATTR_FILE_NAME , file . getName ( ) ) ; String fileExtension = S . fileExtension ( fileName ) ; MimeType mimeType = MimeType . findByFileExtension ( fileExtension ) ; String type = null != mimeType ? mimeType . type ( ) : null ; sobj . setAttribute ( ATTR_CONTENT_TYPE , type ) ; sobj . setAttribute ( ATTR_CONTENT_LENGTH , S . string ( file . length ( ) ) ) ; return sobj ; } else { return getInvalidObject ( key , new IOException ( "File is a directory or not readable" ) ) ; } } | Construct an SObject with key and file specified | 209 | 9 |
18,131 | public static SObject loadResource ( String url ) { InputStream is = SObject . class . getResourceAsStream ( url ) ; if ( null == is ) { return null ; } String filename = S . afterLast ( url , "/" ) ; if ( S . blank ( filename ) ) { filename = url ; } return of ( randomKey ( ) , is , ATTR_FILE_NAME , filename ) ; } | Load an sobject from classpath by given url path | 89 | 11 |
18,132 | public static SObject of ( String key , String content , String ... attrs ) { SObject sobj = of ( key , content ) ; Map < String , String > map = C . Map ( attrs ) ; sobj . setAttributes ( map ) ; return sobj ; } | Construct an sobject with key content and attributes specified in sequence key1 val1 key2 val2 ... | 60 | 21 |
18,133 | public static SObject of ( String key , byte [ ] buf , int len ) { if ( len <= 0 ) { return of ( key , new byte [ 0 ] ) ; } if ( len >= buf . length ) { return of ( key , buf ) ; } byte [ ] ba = new byte [ len ] ; System . arraycopy ( buf , 0 , ba , 0 , len ) ; return of ( key , ba ) ; } | Construct an SObject with specified key byte array and number of bytes | 92 | 13 |
18,134 | public static String typeOfSuffix ( String fileExtension ) { MimeType mimeType = indexByFileExtension . get ( fileExtension ) ; return null == mimeType ? fileExtension : mimeType . type ; } | Return a content type string corresponding to a given file extension suffix . | 53 | 13 |
18,135 | public List < String > preview ( int limit , boolean noHeaderLine ) { E . illegalArgumentIf ( limit < 1 , "limit must be positive integer" ) ; return fetch ( noHeaderLine ? 1 : 0 , limit ) ; } | Returns first limit lines . | 51 | 5 |
18,136 | public String fetch ( int lineNumber ) { E . illegalArgumentIf ( lineNumber < 0 , "line number must not be negative number: " + lineNumber ) ; E . illegalArgumentIf ( lineNumber >= lines ( ) , "line number is out of range: " + lineNumber ) ; List < String > list = fetch ( lineNumber , 1 ) ; return list . isEmpty ( ) ? null : list . get ( 0 ) ; } | Returns the line specified by lineNumber . | 96 | 8 |
18,137 | public List < String > fetch ( int offset , int limit ) { E . illegalArgumentIf ( offset < 0 , "offset must not be negative number" ) ; E . illegalArgumentIf ( offset >= lines ( ) , "offset is out of range: " + offset ) ; E . illegalArgumentIf ( limit < 1 , "limit must be at least 1" ) ; BufferedReader reader = IO . buffered ( IO . reader ( file ) ) ; try { for ( int i = 0 ; i < offset ; ++ i ) { if ( null == reader . readLine ( ) ) { break ; } } } catch ( IOException e ) { throw E . ioException ( e ) ; } List < String > lines = new ArrayList <> ( ) ; try { for ( int i = 0 ; i < limit ; ++ i ) { String line = reader . readLine ( ) ; if ( null == line ) { break ; } lines . add ( line ) ; } } catch ( IOException e ) { throw E . ioException ( e ) ; } return lines ; } | Returns a number of lines specified by start position offset and limit . | 231 | 13 |
18,138 | public static Map < String , Class > buildTypeParamImplLookup ( Class theClass ) { Map < String , Class > lookup = new HashMap <> ( ) ; buildTypeParamImplLookup ( theClass , lookup ) ; return lookup ; } | Build class type variable name and type variable implementation lookup | 53 | 10 |
18,139 | public static String encodeUrlSafeBase64 ( String value ) { return new String ( UrlSafeBase64 . encode ( value . getBytes ( Charsets . UTF_8 ) ) ) ; } | Encode a String to base64 using variant URL safe encode scheme | 42 | 13 |
18,140 | public static String hexMD5 ( String value ) { try { MessageDigest messageDigest = MessageDigest . getInstance ( "MD5" ) ; messageDigest . reset ( ) ; messageDigest . update ( value . getBytes ( "utf-8" ) ) ; byte [ ] digest = messageDigest . digest ( ) ; return byteToHexString ( digest ) ; } catch ( Exception ex ) { throw new UnexpectedException ( ex ) ; } } | Build an hexadecimal MD5 hash for a String | 101 | 12 |
18,141 | public static String hexSHA1 ( String value ) { try { MessageDigest md ; md = MessageDigest . getInstance ( "SHA-1" ) ; md . update ( value . getBytes ( "utf-8" ) ) ; byte [ ] digest = md . digest ( ) ; return byteToHexString ( digest ) ; } catch ( Exception ex ) { throw new UnexpectedException ( ex ) ; } } | Build an hexadecimal SHA1 hash for a String | 90 | 12 |
18,142 | public static void NPE ( Object o1 , Object o2 , Object o3 , Object ... objects ) { NPE ( o1 , o2 , o3 ) ; for ( Object o : objects ) { if ( null == o ) { throw new NullPointerException ( ) ; } } } | Throw out NullPointerException if any one of the passed objects is null . | 63 | 16 |
18,143 | public static RuntimeException asRuntimeException ( Exception e ) { if ( e instanceof RuntimeException ) { return ( RuntimeException ) e ; } return UnexpectedMethodInvocationException . triage ( e ) ; } | Convert an Exception to RuntimeException | 44 | 7 |
18,144 | public Stream < JsonObject > parseJsonLines ( Reader r ) { return StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( jsonLinesIterator ( r ) , Spliterator . ORDERED ) , false ) ; } | Use this to parse jsonlines . org style input . IMPORTANT you have to close the reader yourself with a try ... finally . | 51 | 27 |
18,145 | public static org . w3c . dom . Document getW3cDocument ( JsonElement value , String rootName ) { Element root = getElement ( value , rootName ) ; try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; DOMImplementation impl = builder . getDOMImplementation ( ) ; return DOMConverter . convert ( new Document ( root ) , impl ) ; } catch ( ParserConfigurationException e ) { throw new IllegalStateException ( e ) ; } } | Convert any JsonElement into an w3c DOM tree . | 130 | 14 |
18,146 | public @ Nonnull JsonBuilder put ( String key , String s ) { object . put ( key , primitive ( s ) ) ; return this ; } | Add a string value to the object . | 32 | 8 |
18,147 | public @ Nonnull JsonBuilder put ( String key , boolean b ) { object . put ( key , primitive ( b ) ) ; return this ; } | Add a boolean value to the object . | 32 | 8 |
18,148 | public @ Nonnull JsonBuilder put ( String key , Number n ) { object . put ( key , primitive ( n ) ) ; return this ; } | Add a number to the object . | 32 | 7 |
18,149 | public @ Nonnull JsonBuilder putArray ( String key , String ... values ) { JsonArray jjArray = new JsonArray ( ) ; for ( String string : values ) { jjArray . add ( primitive ( string ) ) ; } object . put ( key , jjArray ) ; return this ; } | Add a JsonArray to the object with the string values added . | 68 | 14 |
18,150 | public static @ Nonnull Entry < String , JsonElement > field ( String key , JsonElement value ) { Entry < String , JsonElement > entry = new Entry < String , JsonElement > ( ) { @ Override public String getKey ( ) { return key ; } @ Override public JsonElement getValue ( ) { return value ; } @ Override public JsonElement setValue ( JsonElement value ) { throw new UnsupportedOperationException ( "entries are immutable" ) ; } } ; return entry ; } | Create a new field that can be added to a JsonObject . | 114 | 14 |
18,151 | public static @ Nonnull Entry < String , JsonElement > field ( String key , Object value ) { return field ( key , fromObject ( value ) ) ; } | Create a new field with the key and the result of fromObject on the value . | 35 | 17 |
18,152 | public JsonElement get ( String label ) { int i = 0 ; try { for ( JsonElement e : this ) { if ( e . isPrimitive ( ) && e . asPrimitive ( ) . asString ( ) . equals ( label ) ) { return e ; } else if ( ( e . isObject ( ) || e . isArray ( ) ) && Integer . valueOf ( label ) . equals ( i ) ) { return e ; } i ++ ; } } catch ( NumberFormatException e ) { // fail gracefully return null ; } // the element was not found return null ; } | Convenient method providing a few alternate ways of extracting elements from a JsonArray . | 128 | 17 |
18,153 | public boolean replace ( JsonElement e1 , JsonElement e2 ) { int index = indexOf ( e1 ) ; if ( index >= 0 ) { set ( index , e2 ) ; return true ; } else { return false ; } } | Replaces the first matching element . | 53 | 7 |
18,154 | public boolean replace ( Object e1 , Object e2 ) { return replace ( fromObject ( e1 ) , fromObject ( e2 ) ) ; } | Replaces the element . | 32 | 5 |
18,155 | public boolean replaceObject ( JsonObject e1 , JsonObject e2 , String ... path ) { JsonElement compareElement = e1 . get ( path ) ; if ( compareElement == null ) { throw new IllegalArgumentException ( "specified path may not be null in object " + StringUtils . join ( path ) ) ; } int i = 0 ; for ( JsonElement e : this ) { if ( e . isObject ( ) ) { JsonElement fieldValue = e . asObject ( ) . get ( path ) ; if ( compareElement . equals ( fieldValue ) ) { set ( i , e2 ) ; return true ; } } i ++ ; } return false ; } | Convenient replace method that allows you to replace an object based on field equality for a specified field . Useful if you have an id field in your objects . Note the array may contain non objects as well or objects without the specified field . Those elements won t be replaced of course . | 149 | 56 |
18,156 | public @ Nonnull Iterable < JsonObject > objects ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < JsonObject > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public JsonObject next ( ) { return iterator . next ( ) . asObject ( ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } ; } | Convenience method to prevent casting JsonElement to JsonObject when iterating in the common case that you have an array of JsonObjects . | 120 | 32 |
18,157 | public @ Nonnull Iterable < JsonArray > arrays ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < JsonArray > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public JsonArray next ( ) { return iterator . next ( ) . asArray ( ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } ; } | Convenience method to prevent casting JsonElement to JsonArray when iterating in the common case that you have an array of JsonArrays . | 120 | 32 |
18,158 | public @ Nonnull Iterable < String > strings ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < String > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public String next ( ) { return iterator . next ( ) . asString ( ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } ; } | Convenience method to prevent casting JsonElement to String when iterating in the common case that you have an array of strings . | 114 | 27 |
18,159 | public @ Nonnull Iterable < Double > doubles ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < Double > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public Double next ( ) { return iterator . next ( ) . asDouble ( ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } ; } | Convenience method to prevent casting JsonElement to Double when iterating in the common case that you have an array of doubles . | 114 | 27 |
18,160 | @ Override public void add ( final String ... elements ) { for ( String s : elements ) { JsonPrimitive primitive = primitive ( s ) ; if ( ! contains ( primitive ) ) { add ( primitive ) ; } } } | Variant of add that adds multiple strings . | 49 | 9 |
18,161 | @ Override public boolean add ( final String s ) { JsonPrimitive primitive = primitive ( s ) ; if ( ! contains ( primitive ) ) { return add ( primitive ) ; } else { return false ; } } | Variant of add that takes a string instead of a JsonElement . The inherited add only supports JsonElement . | 46 | 24 |
18,162 | public JsonSet withIdStrategy ( IdStrategy strategy ) { this . strategy = strategy ; if ( size ( ) > 0 ) { JsonSet seen = new JsonSet ( ) . withIdStrategy ( strategy ) ; Iterator < JsonElement > iterator = this . iterator ( ) ; while ( iterator . hasNext ( ) ) { JsonElement e = iterator . next ( ) ; if ( seen . contains ( e ) ) { iterator . remove ( ) ; } else { seen . add ( e ) ; } } } return this ; } | Changes the strategy on the current set . | 119 | 8 |
18,163 | public static WrappedRequest wrap ( final HttpServletRequest request ) throws IOException { if ( request instanceof WrappedRequest ) { return ( WrappedRequest ) request ; } return new WrappedRequest ( request ) ; } | Factory method used to create a WrappedRequest wrapping a HttpServletRequest . | 48 | 17 |
18,164 | public boolean accept ( Class < ? > aClass ) { try { return ( testKryo . getRegistration ( aClass ) != null ) ; } catch ( IllegalArgumentException e ) { return false ; } } | Uses the initialized Kryo instance from the JobConf to test if Kryo will accept the class | 46 | 20 |
18,165 | public static String getNameSpaceName ( String pageTitle ) { Matcher matcher = namespacePattern . matcher ( pageTitle ) ; if ( matcher . find ( ) ) { // LOGGER.log(Level.INFO,pageTitle); return matcher . group ( 1 ) ; } return null ; } | get the name space name | 65 | 5 |
18,166 | @ XmlElementWrapper ( name = "revisions" ) @ XmlElement ( name = "rev" , type = Rev . class ) public List < Rev > getRevisions ( ) { return revisions ; } | Gets the value of the revisions property . | 46 | 9 |
18,167 | @ XmlElementWrapper ( name = "images" ) @ XmlElement ( name = "im" , type = Im . class ) public List < Im > getImages ( ) { return images ; } | Gets the value of the images property . | 44 | 9 |
18,168 | @ XmlElementWrapper ( name = "allpages" ) @ XmlElement ( name = "p" , type = P . class ) public List < P > getAllpages ( ) { return allpages ; } | Gets the value of the allpages property . | 47 | 10 |
18,169 | @ XmlElementWrapper ( name = "allimages" ) @ XmlElement ( name = "img" , type = Img . class ) public List < Img > getAllImages ( ) { return allimages ; } | Gets the value of the allimages property . | 49 | 10 |
18,170 | @ XmlElementWrapper ( name = "pages" ) @ XmlElement ( name = "page" , type = Page . class ) public List < Page > getPages ( ) { return pages ; } | Gets the value of the pages property . | 44 | 9 |
18,171 | public void init ( ) throws Exception { // configure the SSLContext with a TrustManager SSLContext ctx = SSLContext . getInstance ( "TLS" ) ; if ( ignoreCertificates ) { ctx . init ( new KeyManager [ 0 ] , new TrustManager [ ] { new DefaultTrustManager ( ) } , new SecureRandom ( ) ) ; SSLContext . setDefault ( ctx ) ; } HostnameVerifier hv = new IgnoreHostName ( ) ; HttpsURLConnection . setDefaultHostnameVerifier ( hv ) ; } | initialize this wiki | 118 | 4 |
18,172 | public void login ( ) throws Exception { WikiUser wuser = WikiUser . getUser ( getWikiid ( ) , getSiteurl ( ) ) ; if ( wuser == null ) { throw new Exception ( "user for " + getWikiid ( ) + "(" + getSiteurl ( ) + ") not configured" ) ; } // wiki.setDebug(true); try { Login login = login ( wuser . getUsername ( ) , wuser . getPassword ( ) ) ; LOGGER . log ( Level . INFO , this . siteurl + this . scriptPath + this . apiPath + ":" + login . getResult ( ) ) ; if ( ! "Success" . equals ( login . getResult ( ) ) ) { throw new Exception ( "login for '" + wuser . getUsername ( ) + "' at '" + getWikiid ( ) + "(" + this . getSiteurl ( ) + this . getScriptPath ( ) + ")' failed: " + login . getResult ( ) ) ; } } catch ( javax . net . ssl . SSLHandshakeException she ) { String msg = "login via SSL to " + this . getSiteurl ( ) + " failed\n" ; msg += "Exception: " + she . getMessage ( ) ; throw new Exception ( msg ) ; } } | log me in with the configured user | 288 | 7 |
18,173 | public Unmarshaller getUnmarshaller ( ) throws JAXBException { JAXBContext context = JAXBContext . newInstance ( classOfT ) ; Unmarshaller u = context . createUnmarshaller ( ) ; u . setEventHandler ( new ValidationEventHandler ( ) { @ Override public boolean handleEvent ( ValidationEvent event ) { return true ; } } ) ; return u ; } | get a fitting Unmarshaller | 98 | 8 |
18,174 | public T fromXML ( String xml ) throws Exception { Unmarshaller u = this . getUnmarshaller ( ) ; u . setProperty ( MarshallerProperties . MEDIA_TYPE , "application/xml" ) ; T result = this . fromString ( u , xml ) ; return result ; } | get an instance of T for the given xml string | 69 | 10 |
18,175 | public T fromJson ( String json ) throws Exception { Unmarshaller u = this . getUnmarshaller ( ) ; u . setProperty ( MarshallerProperties . MEDIA_TYPE , "application/json" ) ; T result = this . fromString ( u , json ) ; return result ; } | get an instance of T for the given json string | 69 | 10 |
18,176 | public String getString ( Marshaller marshaller , T instance ) throws JAXBException { StringWriter sw = new StringWriter ( ) ; marshaller . marshal ( instance , sw ) ; String result = sw . toString ( ) ; return result ; } | get the string representation of the given marshaller | 56 | 10 |
18,177 | protected void initNameSpaces ( General general , List < Ns > namespaceList ) { namespaces = new LinkedHashMap < String , Ns > ( ) ; namespacesById = new LinkedHashMap < Integer , Ns > ( ) ; namespacesByCanonicalName = new LinkedHashMap < String , Ns > ( ) ; for ( Ns namespace : namespaceList ) { String namespacename = namespace . getValue ( ) ; namespaces . put ( namespacename , namespace ) ; namespacesById . put ( namespace . getId ( ) , namespace ) ; String canonical = namespace . getCanonical ( ) ; // this is a BUG in 2015-07-02 - some canonical names are not correct // FIXME - when Bug has been fixed in SMW String bugs [ ] = { "Attribut" , "Property" , "Konzept" , "Concept" , "Kategorie" , "Category" } ; for ( int i = 0 ; i < bugs . length ; i += 2 ) { if ( bugs [ i ] . equals ( canonical ) && bugs [ i ] . equals ( namespacename ) ) { canonical = bugs [ i + 1 ] ; namespace . setCanonical ( bugs [ i + 1 ] ) ; } } namespacesByCanonicalName . put ( canonical , namespace ) ; } } | initialize the NameSpaces from the given namespaceList | 293 | 11 |
18,178 | public String mapNamespace ( String ns , SiteInfo targetWiki ) throws Exception { Map < String , Ns > sourceMap = this . getNamespaces ( ) ; Map < Integer , Ns > targetMap = targetWiki . getNamespacesById ( ) ; Ns sourceNs = sourceMap . get ( ns ) ; if ( sourceNs == null ) { if ( debug ) LOGGER . log ( Level . WARNING , "can not map unknown namespace " + ns ) ; return ns ; } Ns targetNs = targetMap . get ( sourceNs . getId ( ) ) ; if ( targetNs == null ) { if ( debug ) LOGGER . log ( Level . WARNING , "missing namespace " + sourceNs . getValue ( ) + " id:" + sourceNs . getId ( ) + " canonical:" + sourceNs . getCanonical ( ) ) ; return ns ; } return targetNs . getValue ( ) ; } | map the given namespace to the target wiki | 198 | 8 |
18,179 | public static String generateRandomKey ( int pLength ) { int asciiFirst = 48 ; int asciiLast = 122 ; Integer [ ] exceptions = { 58 , 59 , 60 , 61 , 62 , 63 , 91 , 92 , 93 , 94 , 96 } ; List < Integer > exceptionsList = Arrays . asList ( exceptions ) ; SecureRandom random = new SecureRandom ( ) ; StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < pLength ; i ++ ) { int charIndex ; do { charIndex = random . nextInt ( asciiLast - asciiFirst + 1 ) + asciiFirst ; } while ( exceptionsList . contains ( charIndex ) ) ; builder . append ( ( char ) charIndex ) ; } return builder . toString ( ) ; } | generate a Random key | 175 | 5 |
18,180 | public static Crypt getRandomCrypt ( ) { String lCypher = generateRandomKey ( 32 ) ; String lSalt = generateRandomKey ( 8 ) ; Crypt result = new Crypt ( lCypher , lSalt ) ; return result ; } | get a random Crypt | 52 | 4 |
18,181 | String encrypt ( String property ) throws GeneralSecurityException , UnsupportedEncodingException { SecretKeyFactory keyFactory = SecretKeyFactory . getInstance ( "PBEWithMD5AndDES" ) ; SecretKey key = keyFactory . generateSecret ( new PBEKeySpec ( cypher ) ) ; Cipher pbeCipher = Cipher . getInstance ( "PBEWithMD5AndDES" ) ; pbeCipher . init ( Cipher . ENCRYPT_MODE , key , new PBEParameterSpec ( salt , 20 ) ) ; return base64Encode ( pbeCipher . doFinal ( property . getBytes ( "UTF-8" ) ) ) ; } | encrypt the given property | 144 | 5 |
18,182 | public static String getInput ( String name , BufferedReader br ) throws IOException { // prompt the user to enter the given name System . out . print ( "Please Enter " + name + ": " ) ; String value = br . readLine ( ) ; return value ; } | get input from standard in | 59 | 5 |
18,183 | public static File getPropertyFile ( String wikiId , String user ) { String userPropertiesFileName = System . getProperty ( "user.home" ) + "/.mediawiki-japi/" + user + "_" + wikiId + ".ini" ; File propFile = new File ( userPropertiesFileName ) ; return propFile ; } | get the property file for the given wikiId and user | 74 | 11 |
18,184 | public static File getPropertyFile ( String wikiId ) { String user = System . getProperty ( "user.name" ) ; return getPropertyFile ( wikiId , user ) ; } | get the propertyFile for the given wikiId | 39 | 9 |
18,185 | public static Properties getProperties ( String wikiId ) throws FileNotFoundException , IOException { File propFile = getPropertyFile ( wikiId ) ; Properties props = new Properties ( ) ; props . load ( new FileReader ( propFile ) ) ; return props ; } | get the Properties for the given wikiId | 57 | 8 |
18,186 | public static WikiUser getUser ( String wikiId , String siteurl ) { WikiUser result = null ; try { Properties props = getProperties ( wikiId ) ; result = new WikiUser ( ) ; result . setUsername ( props . getProperty ( "user" ) ) ; result . setEmail ( props . getProperty ( "email" ) ) ; Crypt pcf = new Crypt ( props . getProperty ( "cypher" ) , props . getProperty ( "salt" ) ) ; result . setPassword ( pcf . decrypt ( props . getProperty ( "secret" ) ) ) ; } catch ( FileNotFoundException e ) { String msg = help ( wikiId , siteurl ) ; LOGGER . log ( Level . SEVERE , msg ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , e . getMessage ( ) ) ; } catch ( GeneralSecurityException e ) { LOGGER . log ( Level . SEVERE , e . getMessage ( ) ) ; } return result ; } | get the Wiki user for the given wikiid | 224 | 9 |
18,187 | public static void createIniFile ( String ... args ) { try { // open up standard input BufferedReader br = new BufferedReader ( new InputStreamReader ( System . in ) ) ; String wikiid = null ; if ( args . length > 0 ) wikiid = args [ 0 ] ; else wikiid = getInput ( "wiki id" , br ) ; String username = null ; if ( args . length > 1 ) username = args [ 1 ] ; else username = getInput ( "username" , br ) ; String password = null ; if ( args . length > 2 ) password = args [ 2 ] ; else password = getInput ( "password" , br ) ; String email = null ; if ( args . length > 3 ) email = args [ 3 ] ; else email = getInput ( "email" , br ) ; File propFile = getPropertyFile ( wikiid , username ) ; String remember = null ; if ( args . length > 4 ) remember = args [ 4 ] ; else remember = getInput ( "shall i store " + username + "'s credentials encrypted in " + propFile . getName ( ) + " y/n?" , br ) ; if ( remember . trim ( ) . toLowerCase ( ) . startsWith ( "y" ) ) { Crypt lCrypt = Crypt . getRandomCrypt ( ) ; Properties props = new Properties ( ) ; props . setProperty ( "cypher" , lCrypt . getCypher ( ) ) ; props . setProperty ( "salt" , lCrypt . getSalt ( ) ) ; props . setProperty ( "user" , username ) ; props . setProperty ( "email" , email ) ; props . setProperty ( "secret" , lCrypt . encrypt ( password ) ) ; if ( ! propFile . getParentFile ( ) . exists ( ) ) { propFile . getParentFile ( ) . mkdirs ( ) ; } FileOutputStream propsStream = new FileOutputStream ( propFile ) ; props . store ( propsStream , "Mediawiki JAPI credentials for " + wikiid ) ; propsStream . close ( ) ; } } catch ( IOException e1 ) { LOGGER . log ( Level . SEVERE , e1 . getMessage ( ) ) ; } catch ( GeneralSecurityException e1 ) { LOGGER . log ( Level . SEVERE , e1 . getMessage ( ) ) ; } } | create a credentials ini file from the command line | 511 | 10 |
18,188 | @ XmlElementWrapper ( name = "modules" ) @ XmlElement ( name = "module" , type = Module . class ) public List < Module > getModules ( ) { return modules ; } | Ruft den Wert der modules - Eigenschaft ab . | 45 | 15 |
18,189 | @ XmlElementWrapper ( name = "sections" ) @ XmlElement ( name = "s" , type = S . class ) public List < S > getSections ( ) { return sections ; } | Gets the value of the sections property . | 46 | 9 |
18,190 | public static Api fromXML ( final String xml ) throws Exception { Api result = null ; try { result = apifactory . fromXML ( xml ) ; } catch ( JAXBException je ) { LOGGER . log ( Level . SEVERE , je . getMessage ( ) ) ; LOGGER . log ( Level . INFO , xml ) ; throw je ; } return result ; } | create a Api from an XML string | 85 | 8 |
18,191 | public String getIsoTimeStamp ( ) { TimeZone tz = TimeZone . getTimeZone ( "UTC" ) ; DateFormat df = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssX" ) ; df . setTimeZone ( tz ) ; String nowAsISO = df . format ( new Date ( ) ) ; return nowAsISO ; } | get a current IsoTimeStamp | 87 | 8 |
18,192 | public static String getStringFromUrl ( String urlString ) { ApacheHttpClient lclient = ApacheHttpClient . create ( ) ; WebResource webResource = lclient . resource ( urlString ) ; ClientResponse response = webResource . get ( ClientResponse . class ) ; if ( response . getStatus ( ) != 200 ) { throw new RuntimeException ( "HTTP error code : " + response . getStatus ( ) ) ; } String result = response . getEntity ( String . class ) ; return result ; } | get a String from a given URL | 106 | 7 |
18,193 | public Builder getResource ( String queryUrl ) throws Exception { if ( debug ) LOGGER . log ( Level . INFO , queryUrl ) ; WebResource wrs = client . resource ( queryUrl ) ; Builder result = wrs . header ( "USER-AGENT" , USER_AGENT ) ; return result ; } | get the given Builder for the given queryUrl this is a wrapper to be able to debug all QueryUrl | 68 | 21 |
18,194 | public ClientResponse getPostResponse ( String queryUrl , String params , TokenResult token , Object pFormDataObject ) throws Exception { params = params . replace ( "|" , "%7C" ) ; params = params . replace ( "+" , "%20" ) ; // modal handling of post FormDataMultiPart form = null ; MultivaluedMap < String , String > lFormData = null ; if ( pFormDataObject instanceof FormDataMultiPart ) { form = ( FormDataMultiPart ) pFormDataObject ; } else { @ SuppressWarnings ( "unchecked" ) Map < String , String > pFormData = ( Map < String , String > ) pFormDataObject ; lFormData = new MultivaluedMapImpl ( ) ; if ( pFormData != null ) { for ( String key : pFormData . keySet ( ) ) { lFormData . add ( key , pFormData . get ( key ) ) ; } } } if ( token != null ) { switch ( token . tokenMode ) { case token1_24 : if ( lFormData != null ) { lFormData . add ( token . tokenName , token . token ) ; } else { form . field ( token . tokenName , token . token ) ; } break ; default : params += token . asParam ( ) ; } } Builder resource = getResource ( queryUrl + params ) ; // FIXME allow to specify content type (not needed for Mediawiki itself // but // could be good for interfacing ) ClientResponse response = null ; if ( lFormData != null ) { response = resource . type ( MediaType . APPLICATION_FORM_URLENCODED_TYPE ) . post ( ClientResponse . class , lFormData ) ; } else { response = resource . type ( MediaType . MULTIPART_FORM_DATA_TYPE ) . post ( ClientResponse . class , form ) ; } return response ; } | get a Post response | 413 | 4 |
18,195 | public ClientResponse getResponse ( String url , Method method ) throws Exception { Builder resource = getResource ( url ) ; ClientResponse response = null ; switch ( method ) { case Get : response = resource . get ( ClientResponse . class ) ; break ; case Post : response = resource . post ( ClientResponse . class ) ; break ; case Head : response = resource . head ( ) ; break ; case Put : response = resource . put ( ClientResponse . class ) ; break ; } return response ; } | get a response for the given url and method | 104 | 9 |
18,196 | public String getResponseString ( ClientResponse response ) throws Exception { if ( debug ) LOGGER . log ( Level . INFO , "status: " + response . getStatus ( ) ) ; String responseText = response . getEntity ( String . class ) ; if ( response . getStatus ( ) != 200 ) { handleError ( "status " + response . getStatus ( ) + ":'" + responseText + "'" ) ; } return responseText ; } | get the Response string | 96 | 4 |
18,197 | public Map < String , String > getParamMap ( String params ) { Map < String , String > result = new HashMap < String , String > ( ) ; String [ ] paramlist = params . split ( "&" ) ; for ( int i = 0 ; i < paramlist . length ; i ++ ) { String [ ] parts = paramlist [ i ] . split ( "=" ) ; if ( parts . length == 2 ) result . put ( parts [ 0 ] , parts [ 1 ] ) ; } return result ; } | get a Map of parameter from a & delimited parameter list | 112 | 12 |
18,198 | public String getActionResultText ( String action , String params , TokenResult token , Object pFormData , String format ) throws Exception { String queryUrl = siteurl + scriptPath + apiPath + "action=" + action + "&format=" + format ; ClientResponse response ; // decide for the method to use for api access response = this . getPostResponse ( queryUrl , params , token , pFormData ) ; String text = this . getResponseString ( response ) ; return text ; } | get the action result for the given parameters | 104 | 8 |
18,199 | public Api getActionResult ( String action , String params , TokenResult token , Object pFormData , String format ) throws Exception { String text = this . getActionResultText ( action , params , token , pFormData , format ) ; Api api = null ; if ( "xml" . equals ( format ) ) { if ( debug ) { // convert the xml to a more readable format String xmlDebug = text . replace ( ">" , ">\n" ) ; LOGGER . log ( Level . INFO , xmlDebug ) ; } if ( text . startsWith ( "<?xml version" ) ) api = fromXML ( text ) ; else { LOGGER . log ( Level . SEVERE , text ) ; throw new Exception ( "invalid xml:" + text ) ; } } else if ( "json" . equals ( format ) ) { if ( debug ) { LOGGER . log ( Level . INFO , text . substring ( 0 , Math . min ( 240 , text . length ( ) - 1 ) ) ) ; } if ( gson == null ) gson = new Gson ( ) ; api = gson . fromJson ( text , Api . class ) ; api . setRawJson ( text ) ; } else { throw new IllegalStateException ( "unknown format " + format ) ; } return api ; } | get the result for the given action and params | 286 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.