idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
41,000
|
@ SuppressWarnings ( "unchecked" ) public < T > ObjectInstantiator < T > newInstantiatorOf ( Class < T > type ) { try { return ( ObjectInstantiator < T > ) constructor . newInstance ( type ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException e ) { throw new ObjenesisException ( e ) ; } }
|
Return an instantiator for the wanted type and of the one and only type of instantiator returned by this class .
|
41,001
|
public static < T > Class < ? super T > getNonSerializableSuperClass ( Class < T > type ) { Class < ? super T > result = type ; while ( Serializable . class . isAssignableFrom ( result ) ) { result = result . getSuperclass ( ) ; if ( result == null ) { throw new Error ( "Bad class hierarchy: No non-serializable parents" ) ; } } return result ; }
|
Returns the first non - serializable superclass of a given class . According to Java Object Serialization Specification objects read from a stream are initialized by calling an accessible no - arg constructor from the first non - serializable superclass in the object s hierarchy allowing the state of non - serializable fields to be correctly initialized .
|
41,002
|
public static String describePlatform ( ) { String desc = "Java " + SPECIFICATION_VERSION + " (" + "VM vendor name=\"" + VENDOR + "\", " + "VM vendor version=" + VENDOR_VERSION + ", " + "JVM name=\"" + JVM_NAME + "\", " + "JVM version=" + VM_VERSION + ", " + "JVM info=" + VM_INFO ; if ( ANDROID_VERSION != 0 ) { desc += ", API level=" + ANDROID_VERSION ; } desc += ")" ; return desc ; }
|
Describes the platform . Outputs Java version and vendor .
|
41,003
|
private Map < String , TypeName > convertPropertiesToTypes ( Map < String , ExecutableElement > properties ) { Map < String , TypeName > types = new LinkedHashMap < > ( ) ; for ( Map . Entry < String , ExecutableElement > entry : properties . entrySet ( ) ) { ExecutableElement el = entry . getValue ( ) ; types . put ( entry . getKey ( ) , TypeName . get ( el . getReturnType ( ) ) ) ; } return types ; }
|
Converts the ExecutableElement properties to TypeName properties
|
41,004
|
private static String classNameOf ( TypeElement type , String delimiter ) { String name = type . getSimpleName ( ) . toString ( ) ; while ( type . getEnclosingElement ( ) instanceof TypeElement ) { type = ( TypeElement ) type . getEnclosingElement ( ) ; name = type . getSimpleName ( ) + delimiter + name ; } return name ; }
|
Returns the name of the given type including any enclosing types but not the package separated by a delimiter .
|
41,005
|
public static float [ ] checkArrayElementsInRange ( float [ ] value , float lower , float upper , String valueName ) { checkNotNull ( value , valueName + " must not be null" ) ; for ( int i = 0 ; i < value . length ; ++ i ) { float v = value [ i ] ; if ( Float . isNaN ( v ) ) { throw new IllegalArgumentException ( valueName + "[" + i + "] must not be NaN" ) ; } else if ( v < lower ) { throw new IllegalArgumentException ( String . format ( "%s[%d] is out of range of [%f, %f] (too low)" , valueName , i , lower , upper ) ) ; } else if ( v > upper ) { throw new IllegalArgumentException ( String . format ( "%s[%d] is out of range of [%f, %f] (too high)" , valueName , i , lower , upper ) ) ; } } return value ; }
|
Ensures that all elements in the argument floating point array are within the inclusive range
|
41,006
|
private void initializeUserStoreAndCheckVersion ( ) throws Exception { int i = 0 ; String version = com . evernote . edam . userstore . Constants . EDAM_VERSION_MAJOR + "." + com . evernote . edam . userstore . Constants . EDAM_VERSION_MINOR ; for ( String url : mBootstrapServerUrls ) { i ++ ; try { EvernoteUserStoreClient userStoreClient = mEvernoteSession . getEvernoteClientFactory ( ) . getUserStoreClient ( getUserStoreUrl ( url ) , null ) ; if ( ! userStoreClient . checkVersion ( EvernoteUtil . generateUserAgentString ( mEvernoteSession . getApplicationContext ( ) ) , com . evernote . edam . userstore . Constants . EDAM_VERSION_MAJOR , com . evernote . edam . userstore . Constants . EDAM_VERSION_MINOR ) ) { throw new ClientUnsupportedException ( version ) ; } mBootstrapServerUsed = url ; return ; } catch ( ClientUnsupportedException cue ) { Log . e ( LOGTAG , "Invalid Version" , cue ) ; throw cue ; } catch ( Exception e ) { if ( i < mBootstrapServerUrls . size ( ) ) { Log . e ( LOGTAG , "Error contacting bootstrap server=" + url , e ) ; } else { throw e ; } } } }
|
Initialized the User Store to check for supported version of the API .
|
41,007
|
BootstrapInfoWrapper getBootstrapInfo ( ) throws Exception { Log . d ( LOGTAG , "getBootstrapInfo()" ) ; BootstrapInfo bsInfo = null ; try { if ( mBootstrapServerUsed == null ) { initializeUserStoreAndCheckVersion ( ) ; } bsInfo = mEvernoteSession . getEvernoteClientFactory ( ) . getUserStoreClient ( getUserStoreUrl ( mBootstrapServerUsed ) , null ) . getBootstrapInfo ( mLocale . toString ( ) ) ; printBootstrapInfo ( bsInfo ) ; } catch ( TException e ) { Log . e ( LOGTAG , "error getting bootstrap info" , e ) ; } return new BootstrapInfoWrapper ( mBootstrapServerUsed , bsInfo ) ; }
|
Makes a web request to get the latest bootstrap information . This is a requirement during the oauth process
|
41,008
|
public Response fetchEvernoteUrl ( String url ) throws IOException { Request . Builder requestBuilder = new Request . Builder ( ) . url ( url ) . addHeader ( "Cookie" , mAuthHeader ) . get ( ) ; return mHttpClient . newCall ( requestBuilder . build ( ) ) . execute ( ) ; }
|
Fetches the URL with the current authentication token as cookie in the header .
|
41,009
|
public static String createEnMediaTag ( Resource resource ) { return "<en-media hash=\"" + bytesToHex ( resource . getData ( ) . getBodyHash ( ) ) + "\" type=\"" + resource . getMime ( ) + "\"/>" ; }
|
Create an ENML < ; en - media> ; tag for the specified Resource object .
|
41,010
|
public static byte [ ] hash ( byte [ ] body ) { if ( HASH_DIGEST != null ) { return HASH_DIGEST . digest ( body ) ; } else { throw new EvernoteUtilException ( EDAM_HASH_ALGORITHM + " not supported" , new NoSuchAlgorithmException ( EDAM_HASH_ALGORITHM ) ) ; } }
|
Returns an MD5 checksum of the provided array of bytes .
|
41,011
|
public static byte [ ] hash ( InputStream in ) throws IOException { if ( HASH_DIGEST == null ) { throw new EvernoteUtilException ( EDAM_HASH_ALGORITHM + " not supported" , new NoSuchAlgorithmException ( EDAM_HASH_ALGORITHM ) ) ; } byte [ ] buf = new byte [ 1024 ] ; int n ; while ( ( n = in . read ( buf ) ) != - 1 ) { HASH_DIGEST . update ( buf , 0 , n ) ; } return HASH_DIGEST . digest ( ) ; }
|
Returns an MD5 checksum of the contents of the provided InputStream .
|
41,012
|
public static String bytesToHex ( byte [ ] bytes , boolean withSpaces ) { StringBuilder sb = new StringBuilder ( ) ; for ( byte hashByte : bytes ) { int intVal = 0xff & hashByte ; if ( intVal < 0x10 ) { sb . append ( '0' ) ; } sb . append ( Integer . toHexString ( intVal ) ) ; if ( withSpaces ) { sb . append ( ' ' ) ; } } return sb . toString ( ) ; }
|
Takes the provided byte array and converts it into a hexadecimal string with two characters per byte .
|
41,013
|
public static byte [ ] hexToBytes ( String hexString ) { byte [ ] result = new byte [ hexString . length ( ) / 2 ] ; for ( int i = 0 ; i < result . length ; ++ i ) { int offset = i * 2 ; result [ i ] = ( byte ) Integer . parseInt ( hexString . substring ( offset , offset + 2 ) , 16 ) ; } return result ; }
|
Takes a string in hexadecimal format and converts it to a binary byte array . This does no checking of the format of the input so this should only be used after confirming the format or origin of the string . The input string should only contain the hex data two characters per byte .
|
41,014
|
public static void removeAllCookies ( Context context ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { removeAllCookiesV21 ( ) ; } else { removeAllCookiesV14 ( context . getApplicationContext ( ) ) ; } }
|
Removes all cookies for this application .
|
41,015
|
public static EvernoteInstallStatus getEvernoteInstallStatus ( Context context , String action ) { PackageManager packageManager = context . getPackageManager ( ) ; Intent intent = new Intent ( action ) . setPackage ( PACKAGE_NAME ) ; List < ResolveInfo > resolveInfos = packageManager . queryIntentActivities ( intent , PackageManager . MATCH_DEFAULT_ONLY ) ; if ( ! resolveInfos . isEmpty ( ) ) { return validateSignature ( packageManager ) ; } try { packageManager . getPackageInfo ( PACKAGE_NAME , PackageManager . GET_ACTIVITIES ) ; return EvernoteInstallStatus . OLD_VERSION ; } catch ( Exception e ) { return EvernoteInstallStatus . NOT_INSTALLED ; } }
|
Checks if Evernote is installed and if the app can resolve this action .
|
41,016
|
public static Intent createGetBootstrapProfileNameIntent ( Context context , EvernoteSession evernoteSession ) { if ( evernoteSession . isForceAuthenticationInThirdPartyApp ( ) ) { return null ; } EvernoteUtil . EvernoteInstallStatus installStatus = EvernoteUtil . getEvernoteInstallStatus ( context , EvernoteUtil . ACTION_GET_BOOTSTRAP_PROFILE_NAME ) ; if ( ! EvernoteUtil . EvernoteInstallStatus . INSTALLED . equals ( installStatus ) ) { return null ; } return new Intent ( EvernoteUtil . ACTION_GET_BOOTSTRAP_PROFILE_NAME ) . setPackage ( PACKAGE_NAME ) ; }
|
Returns an Intent to query the bootstrap profile name from the main Evernote app . This is useful if you want to use the main app to authenticate the user and he is already signed in .
|
41,017
|
public static String generateUserAgentString ( Context ctx ) { String packageName = null ; int packageVersion = 0 ; try { packageName = ctx . getPackageName ( ) ; packageVersion = ctx . getPackageManager ( ) . getPackageInfo ( packageName , 0 ) . versionCode ; } catch ( PackageManager . NameNotFoundException e ) { CAT . e ( e . getMessage ( ) ) ; } String userAgent = packageName + " Android/" + packageVersion ; Locale locale = java . util . Locale . getDefault ( ) ; if ( locale == null ) { userAgent += " (" + Locale . US + ");" ; } else { userAgent += " (" + locale . toString ( ) + "); " ; } userAgent += "Android/" + Build . VERSION . RELEASE + "; " ; userAgent += Build . MODEL + "/" + Build . VERSION . SDK_INT + ";" ; return userAgent ; }
|
Construct a user - agent string based on the running application and the device and operating system information . This information is included in HTTP requests made to the Evernote service and assists in measuring traffic and diagnosing problems .
|
41,018
|
public synchronized EvernoteHtmlHelper getHtmlHelperDefault ( ) { checkLoggedIn ( ) ; if ( mHtmlHelperDefault == null ) { mHtmlHelperDefault = createHtmlHelper ( mEvernoteSession . getAuthToken ( ) ) ; } return mHtmlHelperDefault ; }
|
Use this method if you want to download a personal note as HTML .
|
41,019
|
public synchronized EvernoteHtmlHelper getHtmlHelperBusiness ( ) throws TException , EDAMUserException , EDAMSystemException { if ( mHtmlHelperBusiness == null ) { authenticateToBusiness ( ) ; mHtmlHelperBusiness = createHtmlHelper ( mBusinessAuthenticationResult . getAuthenticationToken ( ) ) ; } return mHtmlHelperBusiness ; }
|
Use this method if you want to download a business note as HTML .
|
41,020
|
public Note loadNote ( boolean withContent , boolean withResourcesData , boolean withResourcesRecognition , boolean withResourcesAlternateData ) throws TException , EDAMUserException , EDAMSystemException , EDAMNotFoundException { EvernoteNoteStoreClient noteStore = NoteRefHelper . getNoteStore ( this ) ; if ( noteStore == null ) { return null ; } return noteStore . getNote ( mNoteGuid , withContent , withResourcesData , withResourcesRecognition , withResourcesAlternateData ) ; }
|
Loads the concrete note from the server .
|
41,021
|
public synchronized EvernoteClientFactory getEvernoteClientFactory ( ) { if ( mFactoryThreadLocal == null ) { mFactoryThreadLocal = new ThreadLocal < > ( ) ; } if ( mEvernoteClientFactoryBuilder == null ) { mEvernoteClientFactoryBuilder = new EvernoteClientFactory . Builder ( this ) ; } EvernoteClientFactory factory = mFactoryThreadLocal . get ( ) ; if ( factory == null ) { factory = mEvernoteClientFactoryBuilder . build ( ) ; mFactoryThreadLocal . set ( factory ) ; } return factory ; }
|
Returns a factory to create various clients and helper objects to get access to the Evernote API .
|
41,022
|
public void authenticate ( FragmentActivity activity ) { authenticate ( activity , EvernoteLoginFragment . create ( mConsumerKey , mConsumerSecret , mSupportAppLinkedNotebooks , mLocale ) ) ; }
|
Recommended approach to authenticate the user . If the main Evernote app is installed and up to date the app is launched and authenticates the user . Otherwise the old OAuth process is launched and the user needs to enter his credentials .
|
41,023
|
public synchronized boolean logOut ( ) { if ( ! isLoggedIn ( ) ) { return false ; } mAuthenticationResult . clear ( ) ; mAuthenticationResult = null ; EvernoteUtil . removeAllCookies ( getApplicationContext ( ) ) ; return true ; }
|
Clears all stored session information . If the user is not logged in then this is a no - op .
|
41,024
|
public T getValue ( ModelElementInstance modelElement ) { String value ; if ( namespaceUri == null ) { value = modelElement . getAttributeValue ( attributeName ) ; } else { value = modelElement . getAttributeValueNs ( namespaceUri , attributeName ) ; if ( value == null ) { String alternativeNamespace = owningElementType . getModel ( ) . getAlternativeNamespace ( namespaceUri ) ; if ( alternativeNamespace != null ) { value = modelElement . getAttributeValueNs ( alternativeNamespace , attributeName ) ; } } } if ( value == null && defaultValue != null ) { return defaultValue ; } else { return convertXmlValueToModelValue ( value ) ; } }
|
returns the value of the attribute .
|
41,025
|
private Collection < DomElement > getView ( ModelElementInstanceImpl modelElement ) { return modelElement . getDomElement ( ) . getChildElementsByType ( modelElement . getModelInstance ( ) , childElementTypeClass ) ; }
|
Internal method providing access to the view represented by this collection .
|
41,026
|
private void performClearOperation ( ModelElementInstanceImpl modelElement , Collection < DomElement > elementsToRemove ) { Collection < ModelElementInstance > modelElements = ModelUtil . getModelElementCollection ( elementsToRemove , modelElement . getModelInstance ( ) ) ; for ( ModelElementInstance element : modelElements ) { modelElement . removeChildElement ( element ) ; } }
|
the clear operation used by this collection
|
41,027
|
@ SuppressWarnings ( "unchecked" ) public T getReferenceTargetElement ( ModelElementInstance referenceSourceElement ) { String identifier = getReferenceIdentifier ( referenceSourceElement ) ; ModelElementInstance referenceTargetElement = referenceSourceElement . getModelInstance ( ) . getModelElementById ( identifier ) ; if ( referenceTargetElement != null ) { try { return ( T ) referenceTargetElement ; } catch ( ClassCastException e ) { throw new ModelReferenceException ( "Element " + referenceSourceElement + " references element " + referenceTargetElement + " of wrong type. " + "Expecting " + referenceTargetAttribute . getOwningElementType ( ) + " got " + referenceTargetElement . getElementType ( ) ) ; } } else { return null ; } }
|
Get the reference target model element instance
|
41,028
|
public void setReferenceTargetElement ( ModelElementInstance referenceSourceElement , T referenceTargetElement ) { ModelInstance modelInstance = referenceSourceElement . getModelInstance ( ) ; String referenceTargetIdentifier = referenceTargetAttribute . getValue ( referenceTargetElement ) ; ModelElementInstance existingElement = modelInstance . getModelElementById ( referenceTargetIdentifier ) ; if ( existingElement == null || ! existingElement . equals ( referenceTargetElement ) ) { throw new ModelReferenceException ( "Cannot create reference to model element " + referenceTargetElement + ": element is not part of model. Please connect element to the model first." ) ; } else { setReferenceIdentifier ( referenceSourceElement , referenceTargetIdentifier ) ; } }
|
Set the reference target model element instance
|
41,029
|
public void referencedElementUpdated ( ModelElementInstance referenceTargetElement , String oldIdentifier , String newIdentifier ) { for ( ModelElementInstance referenceSourceElement : findReferenceSourceElements ( referenceTargetElement ) ) { updateReference ( referenceSourceElement , oldIdentifier , newIdentifier ) ; } }
|
Update the reference identifier
|
41,030
|
public void referencedElementRemoved ( ModelElementInstance referenceTargetElement , Object referenceIdentifier ) { for ( ModelElementInstance referenceSourceElement : findReferenceSourceElements ( referenceTargetElement ) ) { if ( referenceIdentifier . equals ( getReferenceIdentifier ( referenceSourceElement ) ) ) { removeReference ( referenceSourceElement , referenceTargetElement ) ; } } }
|
Remove the reference if the target element is removed
|
41,031
|
public static List < String > splitCommaSeparatedList ( String text ) { if ( text == null || text . isEmpty ( ) ) { return Collections . emptyList ( ) ; } Matcher matcher = pattern . matcher ( text ) ; List < String > parts = new ArrayList < String > ( ) ; while ( matcher . find ( ) ) { parts . add ( matcher . group ( ) . trim ( ) ) ; } return parts ; }
|
Splits a comma separated list in to single Strings . The list can contain expressions with commas in it .
|
41,032
|
private ModelElementInstance findElementToInsertAfter ( ModelElementInstance elementToInsert ) { List < ModelElementType > childElementTypes = elementType . getAllChildElementTypes ( ) ; List < DomElement > childDomElements = domElement . getChildElements ( ) ; Collection < ModelElementInstance > childElements = ModelUtil . getModelElementCollection ( childDomElements , modelInstance ) ; ModelElementInstance insertAfterElement = null ; int newElementTypeIndex = ModelUtil . getIndexOfElementType ( elementToInsert , childElementTypes ) ; for ( ModelElementInstance childElement : childElements ) { int childElementTypeIndex = ModelUtil . getIndexOfElementType ( childElement , childElementTypes ) ; if ( newElementTypeIndex >= childElementTypeIndex ) { insertAfterElement = childElement ; } else { break ; } } return insertAfterElement ; }
|
Returns the element after which the new element should be inserted in the DOM document .
|
41,033
|
private void unlinkAllReferences ( ) { Collection < Attribute < ? > > attributes = elementType . getAllAttributes ( ) ; for ( Attribute < ? > attribute : attributes ) { Object identifier = attribute . getValue ( this ) ; if ( identifier != null ) { ( ( AttributeImpl < ? > ) attribute ) . unlinkReference ( this , identifier ) ; } } }
|
Removes all reference to this .
|
41,034
|
private void unlinkAllChildReferences ( ) { List < ModelElementType > childElementTypes = elementType . getAllChildElementTypes ( ) ; for ( ModelElementType type : childElementTypes ) { Collection < ModelElementInstance > childElementsForType = getChildElementsByType ( type ) ; for ( ModelElementInstance childElement : childElementsForType ) { ( ( ModelElementInstanceImpl ) childElement ) . unlinkAllReferences ( ) ; } } }
|
Removes every reference to children of this .
|
41,035
|
public static DomDocument getEmptyDocument ( DocumentBuilderFactory documentBuilderFactory ) { try { DocumentBuilder documentBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; return new DomDocumentImpl ( documentBuilder . newDocument ( ) ) ; } catch ( ParserConfigurationException e ) { throw new ModelParseException ( "Unable to create a new document" , e ) ; } }
|
Get an empty DOM document
|
41,036
|
public static DomDocument parseInputStream ( DocumentBuilderFactory documentBuilderFactory , InputStream inputStream ) { try { DocumentBuilder documentBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; documentBuilder . setErrorHandler ( new DomErrorHandler ( ) ) ; return new DomDocumentImpl ( documentBuilder . parse ( inputStream ) ) ; } catch ( ParserConfigurationException e ) { throw new ModelParseException ( "ParserConfigurationException while parsing input stream" , e ) ; } catch ( SAXException e ) { throw new ModelParseException ( "SAXException while parsing input stream" , e ) ; } catch ( IOException e ) { throw new ModelParseException ( "IOException while parsing input stream" , e ) ; } }
|
Create a new DOM document from the input stream
|
41,037
|
@ SuppressWarnings ( "unchecked" ) public static < T extends ModelElementInstance > Collection < T > getModelElementCollection ( Collection < DomElement > view , ModelInstanceImpl model ) { List < ModelElementInstance > resultList = new ArrayList < ModelElementInstance > ( ) ; for ( DomElement element : view ) { resultList . add ( getModelElement ( element , model ) ) ; } return ( Collection < T > ) resultList ; }
|
Get a collection of all model element instances in a view
|
41,038
|
public static int getIndexOfElementType ( ModelElementInstance modelElement , List < ModelElementType > childElementTypes ) { for ( int index = 0 ; index < childElementTypes . size ( ) ; index ++ ) { ModelElementType childElementType = childElementTypes . get ( index ) ; Class < ? extends ModelElementInstance > instanceType = childElementType . getInstanceType ( ) ; if ( instanceType . isAssignableFrom ( modelElement . getClass ( ) ) ) { return index ; } } Collection < String > childElementTypeNames = new ArrayList < String > ( ) ; for ( ModelElementType childElementType : childElementTypes ) { childElementTypeNames . add ( childElementType . getTypeName ( ) ) ; } throw new ModelException ( "New child is not a valid child element type: " + modelElement . getElementType ( ) . getTypeName ( ) + "; valid types are: " + childElementTypeNames ) ; }
|
Find the index of the type of a model element in a list of element types
|
41,039
|
public static Collection < ModelElementType > calculateAllExtendingTypes ( Model model , Collection < ModelElementType > baseTypes ) { Set < ModelElementType > allExtendingTypes = new HashSet < ModelElementType > ( ) ; for ( ModelElementType baseType : baseTypes ) { ModelElementTypeImpl modelElementTypeImpl = ( ModelElementTypeImpl ) model . getType ( baseType . getInstanceType ( ) ) ; modelElementTypeImpl . resolveExtendingTypes ( allExtendingTypes ) ; } return allExtendingTypes ; }
|
Calculate a collection of all extending types for the given base types
|
41,040
|
public static Collection < ModelElementType > calculateAllBaseTypes ( ModelElementType type ) { List < ModelElementType > baseTypes = new ArrayList < ModelElementType > ( ) ; ModelElementTypeImpl typeImpl = ( ModelElementTypeImpl ) type ; typeImpl . resolveBaseTypes ( baseTypes ) ; return baseTypes ; }
|
Calculate a collection of all base types for the given type
|
41,041
|
public static void setNewIdentifier ( ModelElementType type , ModelElementInstance modelElementInstance , String newId , boolean withReferenceUpdate ) { Attribute < ? > id = type . getAttribute ( ID_ATTRIBUTE_NAME ) ; if ( id != null && id instanceof StringAttribute && id . isIdAttribute ( ) ) { ( ( StringAttribute ) id ) . setValue ( modelElementInstance , newId , withReferenceUpdate ) ; } }
|
Set new identifier if the type has a String id attribute
|
41,042
|
public static void setGeneratedUniqueIdentifier ( ModelElementType type , ModelElementInstance modelElementInstance , boolean withReferenceUpdate ) { setNewIdentifier ( type , modelElementInstance , ModelUtil . getUniqueIdentifier ( type ) , withReferenceUpdate ) ; }
|
Set unique identifier if the type has a String id attribute
|
41,043
|
public static < T > T createInstance ( Class < T > type , Object ... parameters ) { Class < ? > [ ] parameterTypes = new Class < ? > [ parameters . length ] ; for ( int i = 0 ; i < parameters . length ; i ++ ) { Object parameter = parameters [ i ] ; parameterTypes [ i ] = parameter . getClass ( ) ; } try { Constructor < T > constructor = type . getConstructor ( parameterTypes ) ; return constructor . newInstance ( parameters ) ; } catch ( Exception e ) { throw new ModelException ( "Exception while creating an instance of type " + type , e ) ; } }
|
Create a new instance of the provided type
|
41,044
|
public void resolveExtendingTypes ( Set < ModelElementType > allExtendingTypes ) { for ( ModelElementType modelElementType : extendingTypes ) { ModelElementTypeImpl modelElementTypeImpl = ( ModelElementTypeImpl ) modelElementType ; if ( ! allExtendingTypes . contains ( modelElementTypeImpl ) ) { allExtendingTypes . add ( modelElementType ) ; modelElementTypeImpl . resolveExtendingTypes ( allExtendingTypes ) ; } } }
|
Resolve all types recursively which are extending this type
|
41,045
|
public void resolveBaseTypes ( List < ModelElementType > baseTypes ) { if ( baseType != null ) { baseTypes . add ( baseType ) ; baseType . resolveBaseTypes ( baseTypes ) ; } }
|
Resolve all types which are base types of this type
|
41,046
|
public boolean isBaseTypeOf ( ModelElementType elementType ) { if ( this . equals ( elementType ) ) { return true ; } else { Collection < ModelElementType > baseTypes = ModelUtil . calculateAllBaseTypes ( elementType ) ; return baseTypes . contains ( this ) ; } }
|
Test if a element type is a base type of this type . So this type extends the given element type .
|
41,047
|
public Collection < Attribute < ? > > getAllAttributes ( ) { List < Attribute < ? > > allAttributes = new ArrayList < Attribute < ? > > ( ) ; allAttributes . addAll ( getAttributes ( ) ) ; Collection < ModelElementType > baseTypes = ModelUtil . calculateAllBaseTypes ( this ) ; for ( ModelElementType baseType : baseTypes ) { allAttributes . addAll ( baseType . getAttributes ( ) ) ; } return allAttributes ; }
|
Returns a list of all attributes including the attributes of all base types .
|
41,048
|
public Attribute < ? > getAttribute ( String attributeName ) { for ( Attribute < ? > attribute : getAllAttributes ( ) ) { if ( attribute . getAttributeName ( ) . equals ( attributeName ) ) { return attribute ; } } return null ; }
|
Return the attribute for the attribute name
|
41,049
|
private void protectAgainstXxeAttacks ( final DocumentBuilderFactory dbf ) { try { dbf . setFeature ( "http://xml.org/sax/features/external-general-entities" , false ) ; } catch ( ParserConfigurationException ignored ) { } try { dbf . setFeature ( "http://apache.org/xml/features/disallow-doctype-decl" , true ) ; } catch ( ParserConfigurationException ignored ) { } try { dbf . setFeature ( "http://xml.org/sax/features/external-parameter-entities" , false ) ; } catch ( ParserConfigurationException ignored ) { } dbf . setXIncludeAware ( false ) ; dbf . setExpandEntityReferences ( false ) ; }
|
Configures the DocumentBuilderFactory in a way that it is protected against XML External Entity Attacks . If the implementing parser does not support one or multiple features the failed feature is ignored . The parser might not protected if the feature assignment fails .
|
41,050
|
public void validateModel ( DomDocument document ) { Schema schema = getSchema ( document ) ; if ( schema == null ) { return ; } Validator validator = schema . newValidator ( ) ; try { synchronized ( document ) { validator . validate ( document . getDomSource ( ) ) ; } } catch ( IOException e ) { throw new ModelValidationException ( "Error during DOM document validation" , e ) ; } catch ( SAXException e ) { throw new ModelValidationException ( "DOM document is not valid" , e ) ; } }
|
Validate DOM document
|
41,051
|
private boolean requiresFullyQualifiedName ( ) { String currentPackage = PackageScope . get ( ) ; if ( currentPackage != null ) { if ( definition != null && definition . getPackageName ( ) != null && definition . getFullyQualifiedName ( ) != null ) { String conflictingFQCN = getDefinition ( ) . getFullyQualifiedName ( ) . replace ( definition . getPackageName ( ) , currentPackage ) ; if ( ! conflictingFQCN . equals ( getFullyQualifiedName ( ) ) && DefinitionRepository . getRepository ( ) . getDefinition ( conflictingFQCN ) != null ) { return true ; } } } Map < String , String > referenceMap = DefinitionRepository . getRepository ( ) . getReferenceMap ( ) ; if ( referenceMap != null && referenceMap . containsKey ( definition . getName ( ) ) ) { String fqn = referenceMap . get ( definition . getName ( ) ) ; if ( ! getDefinition ( ) . getFullyQualifiedName ( ) . equals ( fqn ) ) { return true ; } } return false ; }
|
Checks if the ref needs to be done by fully qualified name . Why? Because an other reference to a class with the same name but different package has been made already .
|
41,052
|
@ SuppressWarnings ( "static-method" ) public void addOperationToGroup ( String tag , String resourcePath , Operation operation , CodegenOperation co , Map < String , List < CodegenOperation > > operations ) { String prefix = co . returnBaseType != null && co . returnBaseType . contains ( "." ) ? co . returnBaseType . substring ( 0 , co . returnBaseType . lastIndexOf ( "." ) ) : "" ; String newTag = ! prefix . isEmpty ( ) ? prefix + "." + tag : tag ; super . addOperationToGroup ( newTag , resourcePath , operation , co , operations ) ; }
|
Add operation to group
|
41,053
|
private void checkConstructorArguments ( int arguments ) { if ( arguments == 0 && ( typeDef . getConstructors ( ) == null || typeDef . getConstructors ( ) . isEmpty ( ) ) ) { return ; } for ( Method m : typeDef . getConstructors ( ) ) { int a = m . getArguments ( ) != null ? m . getArguments ( ) . size ( ) : 0 ; if ( a == arguments ) { return ; } } throw new IllegalArgumentException ( "No constructor found for " + typeDef . getName ( ) + " with " + arguments + " arguments." ) ; }
|
Checks that a constructor with the required number of arguments is found .
|
41,054
|
private void checkFactoryMethodArguments ( int arguments ) { for ( Method m : typeDef . getMethods ( ) ) { int a = m . getArguments ( ) != null ? m . getArguments ( ) . size ( ) : 0 ; if ( m . getName ( ) . equals ( staticFactoryMethod ) && a == arguments && m . isStatic ( ) ) { return ; } } throw new IllegalArgumentException ( "No static method found on " + typeDef . getName ( ) + " with name " + staticFactoryMethod + " and " + arguments + " arguments." ) ; }
|
Checks that a factory method with the required number of arguments is found .
|
41,055
|
private static boolean classExists ( TypeDef typeDef ) { try { Class . forName ( typeDef . getFullyQualifiedName ( ) ) ; return true ; } catch ( ClassNotFoundException e ) { return false ; } }
|
Checks if class already exists .
|
41,056
|
private static List < Method > adaptConstructors ( List < Method > methods , TypeDef target ) { List < Method > adapted = new ArrayList < Method > ( ) ; for ( Method m : methods ) { adapted . add ( new MethodBuilder ( m ) . withName ( null ) . withReturnType ( target . toUnboundedReference ( ) ) . build ( ) ) ; } return adapted ; }
|
The method adapts constructor method to the current class . It unsets any name that may be presetn in the method . It also sets as a return type a reference to the current type .
|
41,057
|
public String getFullyQualifiedName ( ) { StringBuilder sb = new StringBuilder ( ) ; if ( packageName != null && ! packageName . isEmpty ( ) ) { sb . append ( getPackageName ( ) ) . append ( "." ) ; } if ( outerType != null ) { sb . append ( outerType . getName ( ) ) . append ( "." ) ; } sb . append ( getName ( ) ) ; return sb . toString ( ) ; }
|
Returns the fully qualified name of the type .
|
41,058
|
private static String convertReference ( String ref , TypeDef source , TypeDef target , TypeDef targetBuilder ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "new " ) . append ( targetBuilder . getName ( ) ) . append ( "(" ) . append ( convertReference ( ref , source , target ) ) . append ( ")" ) ; return sb . toString ( ) ; }
|
Converts a reference from the source type to the target type by using the builder .
|
41,059
|
private static String convertMap ( String ref , TypeDef source , TypeDef target ) { Method ctor = BuilderUtils . findBuildableConstructor ( target ) ; String arguments = ctor . getArguments ( ) . stream ( ) . map ( p -> readMapValue ( ref , source , p ) ) . collect ( joining ( ",\n" , "\n" , "" ) ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "new " ) . append ( target . getFullyQualifiedName ( ) ) . append ( "(" ) . append ( arguments ) . append ( ")" ) ; return sb . toString ( ) ; }
|
Converts a map describing the source type to the target .
|
41,060
|
private static String readObjectArrayValue ( String ref , TypeDef source , Property property ) { StringBuilder sb = new StringBuilder ( ) ; Method getter = getterOf ( source , property ) ; TypeRef getterTypeRef = getter . getReturnType ( ) ; TypeRef propertyTypeRef = property . getTypeRef ( ) ; if ( propertyTypeRef instanceof ClassRef && getterTypeRef instanceof ClassRef ) { String nextRef = variables . pop ( ) ; try { TypeDef propertyType = ( ( ClassRef ) propertyTypeRef ) . getDefinition ( ) ; TypeDef getterType = ( ( ClassRef ) getterTypeRef ) . getDefinition ( ) ; sb . append ( indent ( ref ) ) . append ( "Arrays.stream(" ) . append ( "(Map[])(" + ref + " instanceof Map ? ((Map)" + ref + ").getOrDefault(\"" + getterOf ( source , property ) . getName ( ) + "\" , new Map[0]) : new Map[0]))" ) . append ( ".map(" ) . append ( nextRef ) . append ( " ->" ) . append ( convertMap ( nextRef , getterType , propertyType ) ) . append ( ")" ) . append ( ".toArray(size-> new " + propertyType . getFullyQualifiedName ( ) + "[size])" ) ; } finally { variables . push ( nextRef ) ; } return sb . toString ( ) ; } throw new IllegalArgumentException ( "Expected an object property and a matching object getter!!" ) ; }
|
Returns the string representation of the code that reads an object array property .
|
41,061
|
public static boolean hasMethod ( TypeDef typeDef , String method ) { return unrollHierarchy ( typeDef ) . stream ( ) . flatMap ( h -> h . getMethods ( ) . stream ( ) ) . filter ( m -> method . equals ( m . getName ( ) ) ) . findAny ( ) . isPresent ( ) ; }
|
Check if method exists on the specified type .
|
41,062
|
public static boolean hasProperty ( TypeDef typeDef , String property ) { return unrollHierarchy ( typeDef ) . stream ( ) . flatMap ( h -> h . getProperties ( ) . stream ( ) ) . filter ( p -> property . equals ( p . getName ( ) ) ) . findAny ( ) . isPresent ( ) ; }
|
Checks if property exists on the specified type .
|
41,063
|
public static Set < TypeDef > unrollHierarchy ( TypeDef typeDef ) { if ( OBJECT . equals ( typeDef ) ) { return new HashSet < > ( ) ; } Set < TypeDef > hierarchy = new HashSet < > ( ) ; hierarchy . add ( typeDef ) ; hierarchy . addAll ( typeDef . getExtendsList ( ) . stream ( ) . flatMap ( s -> unrollHierarchy ( s . getDefinition ( ) ) . stream ( ) ) . collect ( Collectors . toSet ( ) ) ) ; return hierarchy ; }
|
Unrolls the hierararchy of a specified type .
|
41,064
|
public Map < Artifact , Dependency > resolve ( BomConfig config ) throws Exception { Map < Artifact , Dependency > dependencies = new LinkedHashMap < Artifact , Dependency > ( ) ; if ( config != null && config . getImports ( ) != null ) { for ( BomImport bom : config . getImports ( ) ) { Map < Artifact , Dependency > deps = resolve ( bom ) ; for ( Map . Entry < Artifact , Dependency > e : deps . entrySet ( ) ) { if ( ! dependencies . containsKey ( e . getKey ( ) ) ) { dependencies . put ( e . getKey ( ) , e . getValue ( ) ) ; } } } } return dependencies ; }
|
Resolve all imports contained in the given configuration .
|
41,065
|
public static boolean isDescendant ( TypeDef item , TypeDef candidate ) { if ( item == null || candidate == null ) { return false ; } else if ( candidate . isAssignableFrom ( item ) ) { return true ; } return false ; }
|
Checks if a type is an descendant of an other type
|
41,066
|
public static boolean is ( Method method , boolean acceptPrefixless ) { int length = method . getName ( ) . length ( ) ; if ( method . isPrivate ( ) || method . isStatic ( ) ) { return false ; } if ( ! method . getArguments ( ) . isEmpty ( ) ) { return false ; } if ( method . getReturnType ( ) . equals ( VOID ) ) { return false ; } if ( acceptPrefixless ) { return true ; } if ( method . getName ( ) . startsWith ( GET_PREFIX ) ) { return length > GET_PREFIX . length ( ) ; } if ( method . getName ( ) . startsWith ( IS_PREFIX ) && TypeUtils . isBoolean ( method . getReturnType ( ) ) ) { return length > IS_PREFIX . length ( ) ; } if ( method . getName ( ) . startsWith ( SHOULD_PREFIX ) && TypeUtils . isBoolean ( method . getReturnType ( ) ) ) { return length > SHOULD_PREFIX . length ( ) ; } return false ; }
|
Checks if the specified method is a getter .
|
41,067
|
static String readAnyField ( Object obj , String ... names ) { try { for ( String name : names ) { try { Field field = obj . getClass ( ) . getDeclaredField ( name ) ; field . setAccessible ( true ) ; return ( String ) field . get ( obj ) ; } catch ( NoSuchFieldException e ) { } } return null ; } catch ( IllegalAccessException e ) { return null ; } }
|
Read any field that matches the specified name .
|
41,068
|
private static < V , F > Boolean hasCompatibleVisitMethod ( V visitor , F fluent ) { for ( Method method : visitor . getClass ( ) . getMethods ( ) ) { if ( ! method . getName ( ) . equals ( VISIT ) || method . getParameterTypes ( ) . length != 1 ) { continue ; } Class visitorType = method . getParameterTypes ( ) [ 0 ] ; if ( visitorType . isAssignableFrom ( fluent . getClass ( ) ) ) { return true ; } else { return false ; } } return false ; }
|
Checks if the specified visitor has a visit method compatible with the specified fluent .
|
41,069
|
public static final String toPojoName ( String name , String prefix , String suffix ) { LinkedList < String > parts = new LinkedList < > ( Arrays . asList ( name . split ( SPLITTER_REGEX ) ) ) ; if ( parts . isEmpty ( ) ) { return prefix + name + suffix ; } if ( parts . getFirst ( ) . equals ( "I" ) ) { parts . removeFirst ( ) ; } if ( parts . getFirst ( ) . equals ( "Abstract" ) ) { parts . removeFirst ( ) ; } if ( parts . getLast ( ) . equals ( "Interface" ) ) { parts . removeLast ( ) ; } String candidate = join ( parts , "" ) ; if ( name . equals ( candidate ) ) { return prefix + name + suffix ; } return candidate ; }
|
Converts a name of an interface or abstract class to Pojo name . Remove leading I and Abstract or trailing Interface .
|
41,070
|
public void generatePojos ( BuilderContext builderContext , Set < TypeDef > buildables ) { Set < TypeDef > additonalBuildables = new HashSet < > ( ) ; Set < TypeDef > additionalTypes = new HashSet < > ( ) ; for ( TypeDef typeDef : buildables ) { try { if ( typeDef . isInterface ( ) || typeDef . isAnnotation ( ) ) { typeDef = ClazzAs . POJO . apply ( typeDef ) ; builderContext . getDefinitionRepository ( ) . register ( typeDef ) ; builderContext . getBuildableRepository ( ) . register ( typeDef ) ; generateFromResources ( typeDef , Constants . DEFAULT_SOURCEFILE_TEMPLATE_LOCATION ) ; additonalBuildables . add ( typeDef ) ; if ( typeDef . hasAttribute ( ADDITIONAL_BUILDABLES ) ) { for ( TypeDef also : typeDef . getAttribute ( ADDITIONAL_BUILDABLES ) ) { builderContext . getDefinitionRepository ( ) . register ( also ) ; builderContext . getBuildableRepository ( ) . register ( also ) ; generateFromResources ( also , Constants . DEFAULT_SOURCEFILE_TEMPLATE_LOCATION ) ; additonalBuildables . add ( also ) ; } } if ( typeDef . hasAttribute ( ADDITIONAL_TYPES ) ) { for ( TypeDef also : typeDef . getAttribute ( ADDITIONAL_TYPES ) ) { builderContext . getDefinitionRepository ( ) . register ( also ) ; generateFromResources ( also , Constants . DEFAULT_SOURCEFILE_TEMPLATE_LOCATION ) ; additionalTypes . add ( also ) ; } } } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } generateBuildables ( builderContext , additonalBuildables ) ; }
|
Returns true if pojos where generated .
|
41,071
|
public static boolean methodHasArgument ( Method method , Property property ) { for ( Property candidate : method . getArguments ( ) ) { if ( candidate . equals ( property ) ) { return true ; } } return false ; }
|
Checks if method has a specific argument .
|
41,072
|
public static MortarScope getScope ( Context context ) { Object scope = context . getSystemService ( MORTAR_SERVICE ) ; if ( scope == null ) { scope = context . getApplicationContext ( ) . getSystemService ( MORTAR_SERVICE ) ; } return ( MortarScope ) scope ; }
|
Retrieves a MortarScope from the given context . If none is found retrieves a MortarScope from the application context .
|
41,073
|
public boolean hasService ( String serviceName ) { return serviceName . equals ( MORTAR_SERVICE ) || findService ( serviceName , false ) != null ; }
|
Returns true if the service associated with the given name is provided by mortar . It is safe to call this method on destroyed scopes .
|
41,074
|
public < T > T getService ( String serviceName ) { T service = findService ( serviceName , true ) ; if ( service == null ) { throw new IllegalArgumentException ( format ( "No service found named \"%s\"" , serviceName ) ) ; } return service ; }
|
Returns the service associated with the given name .
|
41,075
|
private MortarScope searchFromRoot ( Scoped scoped ) { MortarScope root = this ; while ( root . parent != null ) { root = root . parent ; } List < MortarScope > scopes = new LinkedList < > ( ) ; scopes . add ( root ) ; while ( ! scopes . isEmpty ( ) ) { MortarScope scope = scopes . get ( 0 ) ; if ( scope . tearDowns . contains ( scoped ) ) { return scope ; } scopes . addAll ( scope . children . values ( ) ) ; scopes . remove ( 0 ) ; } return null ; }
|
Find the scope from the root of the hierarchy in which the scoped object is registered .
|
41,076
|
@ SuppressWarnings ( "unchecked" ) public static < T > T getDaggerComponent ( Context context ) { return ( T ) context . getSystemService ( SERVICE_NAME ) ; }
|
Caller is required to know the type of the component for this context .
|
41,077
|
public static < T > T createComponent ( Class < T > componentClass , Object ... dependencies ) { String fqn = componentClass . getName ( ) ; String packageName = componentClass . getPackage ( ) . getName ( ) ; String simpleName = fqn . substring ( packageName . length ( ) + 1 ) ; String generatedName = ( packageName + ".Dagger" + simpleName ) . replace ( '$' , '_' ) ; try { Class < ? > generatedClass = Class . forName ( generatedName ) ; Object builder = generatedClass . getMethod ( "builder" ) . invoke ( null ) ; for ( Method method : builder . getClass ( ) . getDeclaredMethods ( ) ) { Class < ? > [ ] params = method . getParameterTypes ( ) ; if ( params . length == 1 ) { Class < ? > dependencyClass = params [ 0 ] ; for ( Object dependency : dependencies ) { if ( dependencyClass . isAssignableFrom ( dependency . getClass ( ) ) ) { method . invoke ( builder , dependency ) ; break ; } } } } return ( T ) builder . getClass ( ) . getMethod ( "build" ) . invoke ( builder ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
|
Magic method that creates a component with its dependencies set by reflection . Relies on Dagger2 naming conventions .
|
41,078
|
static final DocumentFragment createContent ( Document doc , String text ) { if ( text != null && ( text . contains ( "<" ) || text . contains ( "&" ) ) ) { DocumentBuilder builder = JOOX . builder ( ) ; try { text = text . trim ( ) ; if ( text . startsWith ( "<?xml" ) ) { Document parsed = builder . parse ( new InputSource ( new StringReader ( text ) ) ) ; DocumentFragment fragment = parsed . createDocumentFragment ( ) ; fragment . appendChild ( parsed . getDocumentElement ( ) ) ; return ( DocumentFragment ) doc . importNode ( fragment , true ) ; } else { String wrapped = "<dummy>" + text + "</dummy>" ; Document parsed = builder . parse ( new InputSource ( new StringReader ( wrapped ) ) ) ; DocumentFragment fragment = parsed . createDocumentFragment ( ) ; NodeList children = parsed . getDocumentElement ( ) . getChildNodes ( ) ; while ( children . getLength ( ) > 0 ) { fragment . appendChild ( children . item ( 0 ) ) ; } return ( DocumentFragment ) doc . importNode ( fragment , true ) ; } } catch ( IOException ignore ) { } catch ( SAXException ignore ) { } } return null ; }
|
Create some content in the context of a given document
|
41,079
|
static final String xpath ( Element element ) { StringBuilder sb = new StringBuilder ( ) ; Node iterator = element ; while ( iterator . getNodeType ( ) == Node . ELEMENT_NODE ) { sb . insert ( 0 , "]" ) ; sb . insert ( 0 , siblingIndex ( ( Element ) iterator ) + 1 ) ; sb . insert ( 0 , "[" ) ; sb . insert ( 0 , ( ( Element ) iterator ) . getTagName ( ) ) ; sb . insert ( 0 , "/" ) ; iterator = iterator . getParentNode ( ) ; } return sb . toString ( ) ; }
|
Return an XPath expression describing an element
|
41,080
|
static final java . util . Date parseDate ( String formatted ) { if ( formatted == null || formatted . trim ( ) . equals ( "" ) ) return null ; try { DatatypeFactory factory = DatatypeFactory . newInstance ( ) ; XMLGregorianCalendar calendar = factory . newXMLGregorianCalendar ( formatted ) ; return calendar . toGregorianCalendar ( ) . getTime ( ) ; } catch ( Exception e ) { Matcher matcher = PATTERN_DD_MM_YYYY . matcher ( formatted ) ; if ( matcher . find ( ) ) { String yyyy = matcher . group ( 3 ) ; String mm = matcher . group ( 2 ) ; String dd = matcher . group ( 1 ) ; String hh = defaultIfEmpty ( matcher . group ( 4 ) , "0" ) ; String min = defaultIfEmpty ( matcher . group ( 5 ) , "0" ) ; String ss = defaultIfEmpty ( matcher . group ( 6 ) , "0" ) ; String ms = defaultIfEmpty ( matcher . group ( 7 ) , "0" ) ; return getDate ( Integer . parseInt ( yyyy ) , Integer . parseInt ( mm ) , Integer . parseInt ( dd ) , Integer . parseInt ( hh ) , Integer . parseInt ( min ) , Integer . parseInt ( ss ) , Integer . parseInt ( ms ) ) ; } else { Matcher matcher2 = PATTERN_YYYY_MM_DD . matcher ( formatted ) ; if ( matcher2 . find ( ) ) { String yyyy = matcher2 . group ( 1 ) ; String mm = defaultIfEmpty ( matcher2 . group ( 2 ) , "1" ) ; String dd = defaultIfEmpty ( matcher2 . group ( 3 ) , "1" ) ; String hh = defaultIfEmpty ( matcher2 . group ( 4 ) , "0" ) ; String min = defaultIfEmpty ( matcher2 . group ( 5 ) , "0" ) ; String ss = defaultIfEmpty ( matcher2 . group ( 6 ) , "0" ) ; String ms = defaultIfEmpty ( matcher2 . group ( 7 ) , "0" ) ; return getDate ( Integer . parseInt ( yyyy ) , Integer . parseInt ( mm ) , Integer . parseInt ( dd ) , Integer . parseInt ( hh ) , Integer . parseInt ( min ) , Integer . parseInt ( ss ) , Integer . parseInt ( ms ) ) ; } else { try { return new Date ( Long . parseLong ( formatted ) ) ; } catch ( NumberFormatException ignore ) { return null ; } } } } }
|
Parse any date format
|
41,081
|
Client createClient ( ) throws InterruptedException { Client client = retryTemplate . execute ( this :: tryCreateClient ) ; LOG . info ( "Connected to Elasticsearch cluster '{}'." , clusterName ) ; return client ; }
|
Tries to create a Client connecting to cluster on the given adresses .
|
41,082
|
public Ontology getOntology ( String iri ) { org . molgenis . ontology . core . meta . Ontology ontology = dataService . query ( ONTOLOGY , org . molgenis . ontology . core . meta . Ontology . class ) . eq ( ONTOLOGY_IRI , iri ) . findOne ( ) ; return toOntology ( ontology ) ; }
|
Retrieves an ontology with a specific IRI .
|
41,083
|
@ SuppressWarnings ( "squid:S2083" ) @ PostMapping ( "/importByUrl" ) public ResponseEntity < String > importFileByUrl ( HttpServletRequest request , @ RequestParam ( "url" ) String url , @ RequestParam ( value = "entityTypeId" , required = false ) String entityTypeId , @ RequestParam ( value = "packageId" , required = false ) String packageId , @ RequestParam ( value = "metadataAction" , required = false ) String metadataAction , @ RequestParam ( value = "action" , required = false ) String action , @ RequestParam ( value = "notify" , required = false ) Boolean notify ) throws URISyntaxException { ImportRun importRun ; try { File tmpFile = fileLocationToStoredRenamedFile ( url , entityTypeId ) ; if ( packageId != null && ! dataService . getMeta ( ) . getPackage ( packageId ) . isPresent ( ) ) { return ResponseEntity . badRequest ( ) . contentType ( TEXT_PLAIN ) . body ( MessageFormat . format ( "Package [{0}] does not exist." , packageId ) ) ; } importRun = importFile ( request , tmpFile , metadataAction , action , notify , packageId ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) ) ; return ResponseEntity . badRequest ( ) . contentType ( TEXT_PLAIN ) . body ( e . getMessage ( ) ) ; } return createCreatedResponseEntity ( importRun ) ; }
|
Imports entities present in a file from a URL
|
41,084
|
@ PostMapping ( "/importFile" ) public ResponseEntity < String > importFile ( HttpServletRequest request , @ RequestParam ( value = "file" ) MultipartFile file , @ RequestParam ( value = "entityTypeId" , required = false ) String entityTypeId , @ RequestParam ( value = "packageId" , required = false ) String packageId , @ RequestParam ( value = "metadataAction" , required = false ) String metadataAction , @ RequestParam ( value = "action" , required = false ) String action , @ RequestParam ( value = "notify" , required = false ) Boolean notify ) throws URISyntaxException { ImportRun importRun ; String filename ; try { filename = getFilename ( file . getOriginalFilename ( ) , entityTypeId ) ; File tmpFile ; try ( InputStream inputStream = file . getInputStream ( ) ) { tmpFile = fileStore . store ( inputStream , filename ) ; } if ( packageId != null && ! dataService . getMeta ( ) . getPackage ( packageId ) . isPresent ( ) ) { return ResponseEntity . badRequest ( ) . contentType ( TEXT_PLAIN ) . body ( MessageFormat . format ( "Package [{0}] does not exist." , packageId ) ) ; } importRun = importFile ( request , tmpFile , metadataAction , action , notify , packageId ) ; } catch ( Exception e ) { LOG . error ( e . getMessage ( ) ) ; return ResponseEntity . badRequest ( ) . contentType ( TEXT_PLAIN ) . body ( e . getMessage ( ) ) ; } return createCreatedResponseEntity ( importRun ) ; }
|
Imports entities present in the submitted file
|
41,085
|
public void populate ( Entity entity ) { stream ( entity . getEntityType ( ) . getAllAttributes ( ) ) . filter ( Attribute :: hasDefaultValue ) . forEach ( attr -> populateDefaultValues ( entity , attr ) ) ; }
|
Populates an entity with default values
|
41,086
|
private Map < String , String > getEnvironmentAttributes ( ) { Map < String , String > environmentAttributes = new HashMap < > ( ) ; environmentAttributes . put ( ATTRIBUTE_ENVIRONMENT_TYPE , environment ) ; return environmentAttributes ; }
|
Make sure Spring does not add the attributes as query parameters to the url when doing a redirect . You can do this by introducing an object instead of a string key value pair .
|
41,087
|
public MyEntitiesValidationReport addEntity ( String entityTypeId , boolean importable ) { sheetsImportable . put ( entityTypeId , importable ) ; valid = valid && importable ; if ( importable ) { fieldsImportable . put ( entityTypeId , new ArrayList < > ( ) ) ; fieldsUnknown . put ( entityTypeId , new ArrayList < > ( ) ) ; fieldsRequired . put ( entityTypeId , new ArrayList < > ( ) ) ; fieldsAvailable . put ( entityTypeId , new ArrayList < > ( ) ) ; importOrder . add ( entityTypeId ) ; } return this ; }
|
Creates a new report with an entity added to it .
|
41,088
|
public MyEntitiesValidationReport addAttribute ( String attributeName , AttributeState state ) { if ( getImportOrder ( ) . isEmpty ( ) ) { throw new IllegalStateException ( "Must add entity first" ) ; } String entityTypeId = getImportOrder ( ) . get ( getImportOrder ( ) . size ( ) - 1 ) ; valid = valid && state . isValid ( ) ; switch ( state ) { case IMPORTABLE : addField ( fieldsImportable , entityTypeId , attributeName ) ; break ; case UNKNOWN : addField ( fieldsUnknown , entityTypeId , attributeName ) ; break ; case AVAILABLE : addField ( fieldsAvailable , entityTypeId , attributeName ) ; break ; case REQUIRED : addField ( fieldsRequired , entityTypeId , attributeName ) ; break ; default : throw new UnexpectedEnumException ( state ) ; } return this ; }
|
Creates a new report with an attribute added to the last added entity ;
|
41,089
|
private < R > R tryTwice ( Supplier < R > action ) { try { return action . get ( ) ; } catch ( UnknownIndexException e ) { waitForIndexToBeStable ( ) ; try { return action . get ( ) ; } catch ( UnknownIndexException e1 ) { throw new MolgenisDataException ( format ( "Error executing query, index for entity type '%s' with id '%s' does not exist" , getEntityType ( ) . getLabel ( ) , getEntityType ( ) . getId ( ) ) ) ; } } }
|
Executes an action on an index that may be unstable .
|
41,090
|
private boolean querySupported ( Query < Entity > q ) { return ! containsAnyOperator ( q , unsupportedOperators ) && ! containsComputedAttribute ( q , getEntityType ( ) ) && ! containsNestedQueryRuleField ( q ) ; }
|
Checks if the underlying repository can handle this query . Queries with unsupported operators queries that use attributes with computed values or queries with nested query rule field are delegated to the index .
|
41,091
|
private void updateEntityTypeEntityWithNewAttributeEntity ( String entity , String attribute , Entity attributeEntity ) { EntityType entityEntity = dataService . getEntityType ( entity ) ; Iterable < Attribute > attributes = entityEntity . getOwnAllAttributes ( ) ; entityEntity . set ( ATTRIBUTES , stream ( attributes ) . map ( att -> att . getName ( ) . equals ( attribute ) ? attributeEntity : att ) . collect ( Collectors . toList ( ) ) ) ; dataService . update ( ENTITY_TYPE_META_DATA , entityEntity ) ; }
|
The attribute just got updated but the entity does not know this yet . To reindex this document in elasticsearch update it .
|
41,092
|
public FileMeta ingest ( String entityTypeId , String url , String loader , String jobExecutionID , Progress progress ) { if ( ! "CSV" . equals ( loader ) ) { throw new FileIngestException ( "Unknown loader '" + loader + "'" ) ; } progress . setProgressMax ( 2 ) ; progress . progress ( 0 , "Downloading url '" + url + "'" ) ; File file = fileStoreDownload . downloadFile ( url , jobExecutionID , entityTypeId + ".csv" ) ; progress . progress ( 1 , "Importing..." ) ; FileRepositoryCollection repoCollection = fileRepositoryCollectionFactory . createFileRepositoryCollection ( file ) ; ImportService importService = importServiceFactory . getImportService ( file , repoCollection ) ; EntityImportReport report = importService . doImport ( repoCollection , MetadataAction . UPSERT , ADD_UPDATE_EXISTING , null ) ; progress . status ( "Ingestion of url '" + url + "' done." ) ; Integer count = report . getNrImportedEntitiesMap ( ) . get ( entityTypeId ) ; count = count != null ? count : 0 ; progress . progress ( 2 , "Successfully imported " + count + " " + entityTypeId + " entities." ) ; FileMeta fileMeta = createFileMeta ( jobExecutionID , file ) ; FileIngestJobExecution fileIngestJobExecution = ( FileIngestJobExecution ) progress . getJobExecution ( ) ; fileIngestJobExecution . setFile ( fileMeta ) ; dataService . add ( FILE_META , fileMeta ) ; return fileMeta ; }
|
Imports a csv file defined in the fileIngest entity
|
41,093
|
public static String createId ( Entity vcfEntity ) { String idStr = StringUtils . strip ( vcfEntity . get ( CHROM ) . toString ( ) ) + "_" + StringUtils . strip ( vcfEntity . get ( POS ) . toString ( ) ) + "_" + StringUtils . strip ( vcfEntity . get ( REF ) . toString ( ) ) + "_" + StringUtils . strip ( vcfEntity . get ( ALT ) . toString ( ) ) + "_" + StringUtils . strip ( vcfEntity . get ( ID ) . toString ( ) ) + "_" + StringUtils . strip ( vcfEntity . get ( QUAL ) != null ? vcfEntity . get ( QUAL ) . toString ( ) : "" ) + "_" + StringUtils . strip ( vcfEntity . get ( FILTER ) != null ? vcfEntity . get ( FILTER ) . toString ( ) : "" ) ; MessageDigest messageDigest ; try { messageDigest = MessageDigest . getInstance ( "MD5" ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } byte [ ] md5Hash = messageDigest . digest ( idStr . getBytes ( UTF_8 ) ) ; return Base64 . getUrlEncoder ( ) . withoutPadding ( ) . encodeToString ( md5Hash ) ; }
|
Creates a internal molgenis id from a vcf entity
|
41,094
|
private void updateFailedLoginAttempts ( int numberOfAttempts ) { UserSecret userSecret = getSecret ( ) ; userSecret . setFailedLoginAttempts ( numberOfAttempts ) ; if ( userSecret . getFailedLoginAttempts ( ) >= MAX_FAILED_LOGIN_ATTEMPTS ) { if ( ! ( userSecret . getLastFailedAuthentication ( ) != null && ( Instant . now ( ) . toEpochMilli ( ) < userSecret . getLastFailedAuthentication ( ) . plus ( Duration . ofSeconds ( BLOCKED_USER_INTERVAL ) ) . toEpochMilli ( ) ) ) ) { userSecret . setFailedLoginAttempts ( FAILED_LOGIN_ATTEMPT_ITERATION ) ; } } else { userSecret . setLastFailedAuthentication ( Instant . now ( ) ) ; } runAsSystem ( ( ) -> dataService . update ( USER_SECRET , userSecret ) ) ; }
|
Check if user has 3 or more failed login attempts - > then determine if the user is within the 30 seconds of the last failed login attempt - > if the user is not outside the timeframe than the failed login attempts are set to 1 because it is a failed login attempt When the user has less than 3 failed login attempts - > the last failed login attempt is logged
|
41,095
|
public CompletableFuture < Void > submit ( JobExecution jobExecution , ExecutorService executorService ) { overwriteJobExecutionUser ( jobExecution ) ; Job molgenisJob = saveExecutionAndCreateJob ( jobExecution ) ; Progress progress = jobExecutionRegistry . registerJobExecution ( jobExecution ) ; CompletableFuture < Void > completableFuture = CompletableFuture . runAsync ( ( ) -> runJob ( jobExecution , molgenisJob , progress ) , executorService ) ; return completableFuture . handle ( ( voidResult , throwable ) -> { if ( throwable != null ) { handleJobException ( jobExecution , throwable ) ; } jobExecutionRegistry . unregisterJobExecution ( jobExecution ) ; return voidResult ; } ) ; }
|
Saves execution in the current thread then creates a Job and submits that for asynchronous execution to a specific ExecutorService .
|
41,096
|
Object executeScript ( String jsScript , Map < String , Object > parameters ) { EntityType entityType = entityTypeFactory . create ( "entity" ) ; Set < String > attributeNames = parameters . keySet ( ) ; attributeNames . forEach ( key -> entityType . addAttribute ( attributeFactory . create ( ) . setName ( key ) ) ) ; if ( attributeNames . iterator ( ) . hasNext ( ) ) { entityType . getAttribute ( attributeNames . iterator ( ) . next ( ) ) . setIdAttribute ( true ) ; } Entity entity = new DynamicEntity ( entityType ) ; parameters . forEach ( entity :: set ) ; return jsMagmaScriptEvaluator . eval ( jsScript , entity ) ; }
|
Execute a JavaScript using the Magma API
|
41,097
|
public void writeAttributes ( Iterable < Attribute > attributes ) throws IOException { List < String > attributeNames = Lists . newArrayList ( ) ; List < String > attributeLabels = Lists . newArrayList ( ) ; for ( Attribute attr : attributes ) { attributeNames . add ( attr . getName ( ) ) ; if ( attr . getLabel ( ) != null ) { attributeLabels . add ( attr . getLabel ( ) ) ; } else { attributeLabels . add ( attr . getName ( ) ) ; } } writeAttributes ( attributeNames , attributeLabels ) ; }
|
Use attribute labels as column names
|
41,098
|
public String viewMappingProjects ( Model model ) { model . addAttribute ( "mappingProjects" , mappingService . getAllMappingProjects ( ) ) ; model . addAttribute ( "entityTypes" , getWritableEntityTypes ( ) ) ; model . addAttribute ( "user" , getCurrentUsername ( ) ) ; model . addAttribute ( "admin" , currentUserIsSu ( ) ) ; model . addAttribute ( "importerUri" , menuReaderService . findMenuItemPath ( ImportWizardController . ID ) ) ; return VIEW_MAPPING_PROJECTS ; }
|
Initializes the model with all mapping projects and all entities to the model .
|
41,099
|
@ PostMapping ( "/addMappingProject" ) public String addMappingProject ( @ RequestParam ( "mapping-project-name" ) String name , @ RequestParam ( "target-entity" ) String targetEntity , @ RequestParam ( "depth" ) int depth ) { MappingProject newMappingProject = mappingService . addMappingProject ( name , targetEntity , depth ) ; return "redirect:" + getMappingServiceMenuUrl ( ) + "/mappingproject/" + newMappingProject . getIdentifier ( ) ; }
|
Adds a new mapping project .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.