idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
141,200
public static String fixPropertyValue ( String value ) { // replace with predefined varialebls value = value . replaceAll ( "\\{jk.appname\\}" , JK . getAppName ( ) ) ; return value ; }
Fix property value .
52
4
141,201
public static Object unifyReferences ( final Hashtable hash , Object object ) { final Object itemAtHash = hash . get ( object . hashCode ( ) ) ; if ( itemAtHash == null ) { hash . put ( object . hashCode ( ) , object ) ; } else { object = itemAtHash ; } return object ; }
return unified reference .
71
4
141,202
public static List < Entry > sortHashTable ( final Hashtable < ? , ? > hash , final boolean asc ) { // Put keys and values in to an arraylist using entryset final ArrayList < Entry > myArrayList = new ArrayList ( hash . entrySet ( ) ) ; // Sort the values based on values first and then keys. Collections . sort ( myArrayList , new HashComparator ( asc ) ) ; return myArrayList ; }
Sort hash table .
95
4
141,203
public static String formatProperties ( Properties properties ) { StringBuffer buf = new StringBuffer ( ) ; Set < Object > keySet = properties . keySet ( ) ; for ( Object key : keySet ) { buf . append ( key . toString ( ) . trim ( ) . toUpperCase ( ) . replaceAll ( " " , "_" ) ) ; buf . append ( "=" ) ; buf . append ( properties . get ( key ) ) ; buf . append ( System . getProperty ( "line.separator" ) ) ; } return buf . toString ( ) ; }
Format properties .
125
3
141,204
public static String getStandard ( HELM2Notation helm2notation ) throws HELM1FormatException , MonomerLoadingException , CTKException , ValidationException , ChemistryException { try { String firstSection = setStandardHELMFirstSection ( helm2notation ) ; List < String > ListOfSecondAndThirdSection = setStandardHELMSecondSectionAndThirdSection ( helm2notation . getListOfConnections ( ) ) ; String fourthSection = setStandardHELMFourthSection ( helm2notation . getListOfAnnotations ( ) ) ; return firstSection + "$" + ListOfSecondAndThirdSection . get ( 0 ) + "$" + ListOfSecondAndThirdSection . get ( 1 ) + "$" + fourthSection + "$V2.0" ; } catch ( HELM1ConverterException | NotationException | org . helm . notation2 . parser . exceptionparser . NotationException e ) { e . printStackTrace ( ) ; throw new HELM1FormatException ( e . getMessage ( ) ) ; } }
method to reproduce a standard HELM in HELM1 - Format
225
13
141,205
private static String setStandardHELMFourthSection ( List < AnnotationNotation > annotations ) { StringBuilder sb = new StringBuilder ( ) ; for ( AnnotationNotation annotation : annotations ) { sb . append ( annotation . toHELM2 ( ) + "|" ) ; } if ( sb . length ( ) > 1 ) { sb . setLength ( sb . length ( ) - 1 ) ; } return sb . toString ( ) ; }
method to transform the fourth section into HELM1 - Format
103
12
141,206
public static String getCanonical ( HELM2Notation helm2notation ) throws HELM1FormatException , ChemistryException { Map < String , String > convertsortedIdstoIds ; try { Object [ ] temp = setCanonicalHELMFirstSection ( helm2notation ) ; LOG . info ( "First Section of canonical HELM was generated" ) ; convertsortedIdstoIds = ( Map < String , String > ) temp [ 0 ] ; String firstSection = ( String ) temp [ 1 ] ; String secondSection = setCanonicalHELMSecondSection ( convertsortedIdstoIds , helm2notation . getListOfConnections ( ) ) ; LOG . info ( "Second Section of canonical HELM was generated" ) ; return firstSection + "$" + secondSection + "$" + "" + "$" + "" + "$V2.0" ; } catch ( ClassNotFoundException | IOException | HELM1ConverterException | ValidationException | org . helm . notation2 . parser . exceptionparser . NotationException e ) { e . printStackTrace ( ) ; LOG . error ( "Canonical HELM 1 can not be generated due to HELM2 features" ) ; throw new HELM1FormatException ( "Canonical HELM 1 can not be generated due to HELM2 features " + e . getMessage ( ) + e . getCause ( ) ) ; } }
method to generate from a helm2notation a valid canonical HELM1
309
14
141,207
private static String setCanonicalHELMSecondSection ( Map < String , String > convertsortedIdstoIds , List < ConnectionNotation > connectionNotations ) throws HELM1ConverterException { StringBuilder notation = new StringBuilder ( ) ; for ( ConnectionNotation connectionNotation : connectionNotations ) { /* canonicalize connection */ /* change the id's of the polymers to the sorted ids */ List < String > connections = new ArrayList < String > ( ) ; String source = connectionNotation . getSourceId ( ) . getId ( ) ; String target = connectionNotation . getTargetId ( ) . getId ( ) ; /* pairs will be not shown */ if ( ! ( connectionNotation . toHELM ( ) . equals ( "" ) ) ) { connections . add ( convertConnection ( connectionNotation . toHELM ( ) , source , target , convertsortedIdstoIds ) ) ; connections . add ( convertConnection ( connectionNotation . toReverseHELM ( ) , source , target , convertsortedIdstoIds ) ) ; Collections . sort ( connections ) ; notation . append ( connections . get ( 0 ) + "|" ) ; } } if ( notation . length ( ) > 1 ) { notation . setLength ( notation . length ( ) - 1 ) ; } return notation . toString ( ) ; }
method to generate a canonical HELM 1 connection section
298
10
141,208
private static String convertConnection ( String notation , String source , String target , Map < String , String > convertIds ) throws HELM1ConverterException { try { String test = notation . replace ( source , "one" ) ; test = test . replace ( target , "two" ) ; test = test . replace ( "one" , convertIds . get ( source ) ) ; test = test . replace ( "two" , convertIds . get ( target ) ) ; return test ; } catch ( NullPointerException ex ) { ex . printStackTrace ( ) ; LOG . error ( "Connection can't be downgraded to HELM1-Format" ) ; throw new HELM1ConverterException ( "Connection can't be downgraded to HELM1-Format" ) ; } }
method to convert the polymers ids of the connection
173
11
141,209
private Element getXHELMRootElement ( String resource ) throws JDOMException , IOException { ByteArrayInputStream stream = new ByteArrayInputStream ( resource . getBytes ( ) ) ; SAXBuilder builder = new SAXBuilder ( ) ; Document doc = builder . build ( stream ) ; return doc . getRootElement ( ) ; }
method to get the XHELMRootElement of a document as a string
73
16
141,210
private void updateMonomerStore ( MonomerStore monomerStore ) throws MonomerLoadingException , IOException , MonomerException , ChemistryException { for ( Monomer monomer : monomerStore . getAllMonomersList ( ) ) { MonomerFactory . getInstance ( ) . getMonomerStore ( ) . addNewMonomer ( monomer ) ; // save monomer db to local file after successful update // MonomerFactory . getInstance ( ) . saveMonomerCache ( ) ; } }
method to combine the new MonomerStore to the existing one in case of xHELM as input
110
21
141,211
private HELM2Notation readNotation ( String notation ) throws ParserException , JDOMException , IOException , MonomerException , ChemistryException { /* xhelm notation */ if ( notation . contains ( "<Xhelm>" ) ) { LOG . info ( "xhelm is used as input" ) ; String xhelm = notation ; Element xHELMRootElement = getXHELMRootElement ( xhelm ) ; notation = xHelmNotationParser . getHELMNotationString ( xHELMRootElement ) ; MonomerStore store = xHelmNotationParser . getMonomerStore ( xHELMRootElement ) ; updateMonomerStore ( store ) ; } return HELM2NotationUtils . readNotation ( notation ) ; }
method to read the HELM string the HELM can be in version 1 or 2 or in Xhelm format
168
22
141,212
private HELM2Notation validate ( String helm ) throws ValidationException , ChemistryException { try { /* Read */ HELM2Notation helm2notation = readNotation ( helm ) ; /* Validate */ LOG . info ( "Validation of HELM is starting" ) ; Validation . validateNotationObjects ( helm2notation ) ; LOG . info ( "Validation was successful" ) ; return helm2notation ; } catch ( MonomerException | GroupingNotationException | ConnectionNotationException | PolymerIDsException | ParserException | JDOMException | IOException | NotationException | org . helm . notation2 . parser . exceptionparser . NotationException e ) { e . printStackTrace ( ) ; LOG . info ( "Validation was not successful" ) ; LOG . error ( e . getMessage ( ) ) ; throw new ValidationException ( e . getMessage ( ) ) ; } }
method to validate the HELM - String input
196
9
141,213
public void validateHELM ( String helm ) throws ValidationException , MonomerLoadingException , ChemistryException { validate ( helm ) ; setMonomerFactoryToDefault ( helm ) ; }
method to validate the input HELM - String
40
9
141,214
public String convertStandardHELMToCanonicalHELM ( String notation ) throws HELM1FormatException , ValidationException , MonomerLoadingException , ChemistryException { String result = HELM1Utils . getCanonical ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to convert the input HELM into canonical HELM
72
11
141,215
public String convertIntoStandardHELM ( String notation ) throws HELM1FormatException , ValidationException , MonomerLoadingException , CTKException , ChemistryException { String result = HELM1Utils . getStandard ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to convert the input HELM into a standard HELM
69
12
141,216
public Float calculateExtinctionCoefficient ( String notation ) throws ExtinctionCoefficientException , ValidationException , MonomerLoadingException , ChemistryException { Float result = ExtinctionCoefficient . getInstance ( ) . calculate ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to calculate from a non - ambiguous HELM string the extinction coefficient
69
14
141,217
public String generateFasta ( String notation ) throws FastaFormatException , ValidationException , MonomerLoadingException , ChemistryException { String result = FastaFormat . generateFasta ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to generate FASTA - Formats for all rna and peptide sequences from an HELM input
59
22
141,218
public Double calculateMolecularWeight ( String notation ) throws MonomerLoadingException , BuilderMoleculeException , CTKException , ValidationException , ChemistryException { Double result = MoleculePropertyCalculator . getMolecularWeight ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to calculate from a non - ambiguous HELM input the molecular weight
71
14
141,219
public String getMolecularFormula ( String notation ) throws BuilderMoleculeException , CTKException , ValidationException , MonomerLoadingException , ChemistryException { String result = MoleculePropertyCalculator . getMolecularFormular ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to calculate from a non - ambiguous HELM input the molecular formula
73
14
141,220
public String readPeptide ( String peptide ) throws FastaFormatException , org . helm . notation2 . parser . exceptionparser . NotationException , ChemistryException { return SequenceConverter . readPeptide ( peptide ) . toHELM2 ( ) ; }
method to read a single peptide sequence and generates HELM
60
12
141,221
public String readRNA ( String rna ) throws org . helm . notation2 . parser . exceptionparser . NotationException , FastaFormatException , ChemistryException , org . helm . notation2 . exception . NucleotideLoadingException { return SequenceConverter . readRNA ( rna ) . toHELM2 ( ) ; }
method to read a single rna sequence and generates HELM
71
12
141,222
public byte [ ] generateImageForHELMMolecule ( String notation ) throws BuilderMoleculeException , CTKException , IOException , ValidationException , ChemistryException { byte [ ] result = Images . generateImageHELMMolecule ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to generate a HELM molecule
73
7
141,223
public byte [ ] generateImageForMonomer ( Monomer monomer , boolean showRgroups ) throws BuilderMoleculeException , CTKException , ChemistryException { return Images . generateImageofMonomer ( monomer , showRgroups ) ; }
method to generate an image for a monomer
54
9
141,224
public String generateJSON ( String helm ) throws ValidationException , MonomerLoadingException , ChemistryException , JsonProcessingException { String result = HELM2NotationUtils . toJSON ( validate ( helm ) ) ; setMonomerFactoryToDefault ( helm ) ; return result ; }
method to generate JSON - Output for the HELM
62
10
141,225
private void setMonomerFactoryToDefault ( String helm ) throws MonomerLoadingException , ChemistryException { if ( helm . contains ( "<Xhelm>" ) ) { LOG . info ( "Refresh local Monomer Store in case of Xhelm" ) ; MonomerFactory . refreshMonomerCache ( ) ; } }
method to set the MonomerFactory to the default one this is only done in case of xHELM input
68
23
141,226
public String generateNaturalAnalogSequencePeptide ( String notation ) throws HELM2HandledException , ValidationException , MonomerLoadingException , PeptideUtilsException , org . helm . notation2 . parser . exceptionparser . NotationException , ChemistryException { String result = SequenceConverter . getPeptideNaturalAnalogSequenceFromNotation ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to generate the natural analogue sequence for all peptide - sequences from an HELM input
100
18
141,227
public String generateNaturalAnalogSequenceRNA ( String notation ) throws org . helm . notation2 . parser . exceptionparser . NotationException , HELM2HandledException , ValidationException , MonomerLoadingException , ChemistryException { String result = SequenceConverter . getNucleotideNaturalAnalogSequenceFromNotation ( validate ( notation ) ) ; setMonomerFactoryToDefault ( notation ) ; return result ; }
method to generate the natural analogue sequence for all rna - sequences from an HELM input
91
18
141,228
public String convertMolFileSMILESWithAtomMapping ( String molfile , List < Attachment > attachments ) throws CTKException , ChemistryException { return SMILES . convertMolToSMILESWithAtomMapping ( molfile , attachments ) ; }
method to generate a smiles with atom mapping for a given molfile with the given attachments
61
18
141,229
public static List < MonomerNotation > getListOfMonomerNotation ( List < PolymerNotation > polymers ) { List < MonomerNotation > items = new ArrayList < MonomerNotation > ( ) ; for ( PolymerNotation polymer : polymers ) { items . addAll ( polymer . getListMonomers ( ) ) ; } return items ; }
method to get all MonomerNotations for all given polymers
83
13
141,230
public static List < Monomer > getListOfMonomer ( List < MonomerNotation > monomerNotations ) throws MonomerException , HELM2HandledException , CTKException , NotationException , ChemistryException , MonomerLoadingException { List < Monomer > items = new ArrayList < Monomer > ( ) ; for ( int i = 0 ; i < monomerNotations . size ( ) ; i ++ ) { items . addAll ( Validation . getAllMonomers ( monomerNotations . get ( i ) , i ) ) ; } return items ; }
method to get all monomers for all MonomerNotations
126
12
141,231
public static Monomer getMonomer ( String type , String id , String info ) throws MonomerException , NotationException , ChemistryException { try { if ( id . startsWith ( "[" ) && id . endsWith ( "]" ) ) { id = id . substring ( 1 , id . length ( ) - 1 ) ; } MonomerFactory monomerFactory = MonomerFactory . getInstance ( ) ; MonomerStore monomerStore = monomerFactory . getMonomerStore ( ) ; Monomer monomer ; /* Monomer was saved to the database */ monomer = monomerStore . getMonomer ( type , id ) ; if ( monomer == null ) { /* * smiles check! Maybe the smiles is already included in the data base */ if ( monomerFactory . getSmilesMonomerDB ( ) . get ( id ) != null ) { monomer = monomerFactory . getSmilesMonomerDB ( ) . get ( id ) ; return monomer ; } else { /* This has to be done */ monomer = monomerFactory . getSmilesMonomerDB ( ) . get ( id ) ; if ( monomer == null ) { /* Rgroups information are not given -> only smiles information */ AbstractChemistryManipulator manipulator = Chemistry . getInstance ( ) . getManipulator ( ) ; if ( manipulator . validateSMILES ( id ) ) { if ( type . equals ( Monomer . CHEMICAL_POLYMER_TYPE ) ) { monomer = generateTemporaryMonomer ( id , type , "X" ) ; } else if ( type . equals ( Monomer . PEPTIDE_POLYMER_TYPE ) ) { monomer = generateTemporaryMonomer ( id , type , "X" ) ; } else if ( type . equals ( Monomer . NUCLIEC_ACID_POLYMER_TYPE ) ) { monomer = generateTemporaryMonomer ( id , type , info ) ; } } else { if ( ! id . equals ( "?" ) && ! id . equals ( "X" ) && ! id . equals ( "N" ) ) { throw new MonomerException ( "Defined Monomer is not in the database and also not valid SMILES " + id ) ; } else { return new Monomer ( type , "Undefined" , id , id ) ; } } /* Add new monomer to the database */ MonomerFactory . getInstance ( ) . getMonomerStore ( ) . addNewMonomer ( monomer ) ; MonomerFactory . getInstance ( ) . getSmilesMonomerDB ( ) . put ( monomer . getCanSMILES ( ) , monomer ) ; // save monomer db to local file after successful update // MonomerFactory . getInstance ( ) . saveMonomerCache ( ) ; LOG . info ( "Monomer was added to the database" ) ; } } } try { List < Attachment > idList = monomer . getAttachmentList ( ) ; for ( Attachment att : idList ) { if ( att . getCapGroupSMILES ( ) == null ) { MonomerParser . fillAttachmentInfo ( att ) ; } } } catch ( CTKException | JDOMException ex ) { throw new MonomerException ( "Attachments could not be filled with default attachments" ) ; } return monomer ; } catch ( IOException e ) { e . printStackTrace ( ) ; /* * monomer is not in the database and also not a valid SMILES -> throw * exception */ throw new MonomerException ( "Defined Monomer is not in the database and also not a valid SMILES " + id ) ; } }
method to get the monomer from the database!
802
10
141,232
public static JKLocale valueOf ( final String localeString ) { return localeString . equals ( ARABIC . shortName ) ? ARABIC : ENGLISH ; }
Value of .
40
3
141,233
public String getAuditText ( ) { final StringBuffer b = new StringBuffer ( ) ; b . append ( getOldValue ( ) . replaceAll ( "," , "\n" ) ) ; b . append ( "-----------------------------------------\n" ) ; b . append ( getNewValue ( ) . replaceAll ( "," , "\n" ) ) ; b . append ( "-----------------------------------------\n" ) ; return b . toString ( ) ; }
Gets the audit text .
97
6
141,234
public float calculate ( HELM2Notation helm2notation , int unitType ) throws ExtinctionCoefficientException , ChemistryException { LOG . debug ( "ExtinctionCalculation is starting with the unitType: " + unitType ) ; float result = 0.0f ; List < PolymerNotation > polymerNodes = helm2notation . getListOfPolymers ( ) ; for ( PolymerNotation polymerNode : polymerNodes ) { String polymerType = polymerNode . getPolymerID ( ) . getType ( ) ; float ext = 0.0f ; ArrayList < PolymerNotation > not = new ArrayList < PolymerNotation > ( ) ; not . add ( polymerNode ) ; if ( polymerType . equals ( Monomer . NUCLIEC_ACID_POLYMER_TYPE ) ) { try { ext = calculateExtinctionFromRNA ( MethodsMonomerUtils . getListOfHandledMonomersOnlyBase ( polymerNode . getPolymerElements ( ) . getListOfElements ( ) ) ) ; } catch ( CalculationException | IOException | HELM2HandledException | NotationException e ) { throw new ExtinctionCoefficientException ( e . getMessage ( ) ) ; } if ( unitType == PEPTIDE_UNIT_TYPE ) { ext = ext * UNIT ; } } else if ( polymerType . equals ( Monomer . PEPTIDE_POLYMER_TYPE ) ) { try { ext = calculateExtinctionFromPeptide ( MethodsMonomerUtils . getListOfHandledMonomers ( polymerNode . getPolymerElements ( ) . getListOfElements ( ) ) ) ; } catch ( IOException | HELM2HandledException e ) { throw new ExtinctionCoefficientException ( e . getMessage ( ) ) ; } if ( unitType == RNA_UNIT_TYPE ) { ext = ext / UNIT ; } } result = result + ext ; } return result ; }
method to calculate the extinction coefficient for the whole HELM molecule
433
12
141,235
private static float calculateExtinctionFromRNA ( List < Monomer > monomers ) throws CalculationException , IOException { LOG . debug ( "ExtinctionCalculation of RNA" ) ; float resultSingle = 0.0f ; float resultDi = 0.0f ; String previous = "" ; if ( monomers . size ( ) == 0 ) { throw new CalculationException ( "Input sequence cannot be null" ) ; } else { if ( monomers . size ( ) == 1 ) { if ( monoNucleotideMap . containsKey ( monomers . get ( 0 ) . getNaturalAnalog ( ) ) ) { return monoNucleotideMap . get ( monomers . get ( 0 ) . getNaturalAnalog ( ) ) . floatValue ( ) ; } else { throw new CalculationException ( "Unknown nucleotide found" ) ; } } for ( int i = 0 ; i < monomers . size ( ) ; i ++ ) { if ( i > 0 && i < monomers . size ( ) - 1 ) { if ( monoNucleotideMap . containsKey ( monomers . get ( i ) . getNaturalAnalog ( ) ) ) { Float value = monoNucleotideMap . get ( monomers . get ( i ) . getNaturalAnalog ( ) ) . floatValue ( ) ; resultSingle += ( value . floatValue ( ) * 1.0 ) ; } } if ( previous != "" ) { if ( diNucleotideMap . containsKey ( previous + monomers . get ( i ) . getNaturalAnalog ( ) ) ) { Float value = diNucleotideMap . get ( previous + monomers . get ( i ) . getNaturalAnalog ( ) ) . floatValue ( ) ; resultDi += ( value . floatValue ( ) * 1.0 ) ; } } previous = monomers . get ( i ) . getNaturalAnalog ( ) ; } } resultSingle = BigDecimal . valueOf ( resultSingle ) . floatValue ( ) ; resultDi = BigDecimal . valueOf ( resultDi ) . floatValue ( ) ; return 2 * resultDi - resultSingle ; }
method to calculate the extinction coefficient for rna
453
9
141,236
private static float calculateExtinctionFromPeptide ( List < Monomer > monomers ) throws IOException , HELM2HandledException { if ( null == monomers || monomers . isEmpty ( ) ) { return 0.0f ; } Map < String , Integer > countMap = new HashMap < String , Integer > ( ) ; for ( Monomer monomer : monomers ) { if ( aminoAcidMap . containsKey ( monomer . getAlternateId ( ) ) ) { int count = 1 ; if ( countMap . containsKey ( monomer . getAlternateId ( ) ) ) { count = count + countMap . get ( monomer . getAlternateId ( ) ) ; } countMap . put ( monomer . getAlternateId ( ) , count ) ; } } float result = 0.0f ; Set < String > keys = countMap . keySet ( ) ; for ( Iterator < String > it = keys . iterator ( ) ; it . hasNext ( ) ; ) { String key = it . next ( ) ; int count = countMap . get ( key ) ; float factor = aminoAcidMap . get ( key ) ; result = result + factor * count ; } return BigDecimal . valueOf ( result ) . floatValue ( ) ; }
method to calculate the extinction coefficient for peptide
277
9
141,237
public static boolean isAuthenticed ( String host , int port , String userName , String password ) throws NamingException { log . info ( "isAuthenticed" ) ; // Set up the environment for creating the initial context Hashtable < String , String > env = new Hashtable < String , String > ( ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; env . put ( Context . PROVIDER_URL , "ldap://" + host + ":" + port ) ; env . put ( Context . SECURITY_AUTHENTICATION , "simple" ) ; env . put ( Context . SECURITY_PRINCIPAL , userName + "@" + host ) ; log . info ( env . toString ( ) ) ; env . put ( Context . SECURITY_CREDENTIALS , password ) ; // Create the initial context DirContext ctx = new InitialDirContext ( env ) ; log . info ( "DirContext Init Succ" ) ; boolean result = ctx != null ; if ( ctx != null ) { log . info ( "Closing DirContext" ) ; ctx . close ( ) ; } return result ; }
Checks if is authenticed .
276
7
141,238
protected static String fixKey ( final String key ) { if ( key . startsWith ( getKeyPrefix ( ) ) ) { return key ; } return getKeyPrefix ( ) + "-" + key ; }
Fix key .
45
3
141,239
public static float getFloat ( final String key , final float def ) { try { return systemRoot . getFloat ( fixKey ( key ) , def ) ; } catch ( final Exception e ) { // just eat the exception to avoid any system // crash on system issues return def ; } }
Gets the float .
60
5
141,240
public static Hashtable < String , String > getHashtable ( final String name ) { final Hashtable < String , String > hash = new Hashtable < String , String > ( ) ; try { final String configStr = UserPreferences . get ( fixKey ( name ) , "" ) ; if ( ! configStr . equals ( "" ) ) { final String [ ] rows = configStr . split ( ";" ) ; for ( final String row : rows ) { final String [ ] split = row . split ( ":" ) ; if ( split . length == 2 ) { final String key = split [ 0 ] ; final String value = split [ 1 ] ; hash . put ( key , value ) ; } } } } catch ( final Exception e ) { // just eat the exception to avoid any system crash on system issues } return hash ; }
Gets the hashtable .
176
6
141,241
public static int getInt ( final String key , final int def ) { try { return systemRoot . getInt ( fixKey ( key ) , def ) ; } catch ( final Exception e ) { // just eat the exception to avoid any system crash on system issues return def ; } }
Gets the int .
59
5
141,242
public static void putHashTable ( final String name , final Hashtable hash ) { final Enumeration < String > keys = hash . keys ( ) ; final StringBuffer buf = new StringBuffer ( "" ) ; while ( keys . hasMoreElements ( ) ) { if ( ! buf . toString ( ) . equals ( "" ) ) { // end the previous record buf . append ( ";" ) ; } final String key = keys . nextElement ( ) ; final String value = hash . get ( key ) . toString ( ) ; buf . append ( key + ":" + value ) ; } put ( fixKey ( name ) , buf . toString ( ) ) ; }
Put hash table .
143
4
141,243
public static void setKeyPrefix ( final String keyPrefix ) { UserPreferences . keyPrefix = keyPrefix ; try { systemRoot . sync ( ) ; } catch ( final Exception e ) { JKExceptionUtil . handle ( e ) ; } }
Sets the key prefix .
57
6
141,244
private static void initializeNucleotideTemplates ( ) throws NucleotideLoadingException { InputStream in = null ; File localFile = new File ( LOCAL_NUCLEOTIDE_TEMPLATE_FILE_PATH ) ; Map < String , Map < String , String > > templates = null ; if ( localFile . exists ( ) ) { try { in = new FileInputStream ( localFile ) ; templates = buildNucleotideTemplates ( in ) ; validate ( templates ) ; logger . log ( Level . INFO , LOCAL_NUCLEOTIDE_TEMPLATE_FILE_PATH + " is used for nucleotide templates initialization" ) ; } catch ( Exception e ) { logger . log ( Level . INFO , "Unable to use local nucleotide templates for initialization" ) ; localFile . delete ( ) ; logger . log ( Level . INFO , "Deleted local nucleotide templates file" ) ; } } if ( null == templates ) { in = NucleotideFactory . class . getResourceAsStream ( NUCLEOTIDE_TEMPLATE_XML_RESOURCE ) ; try { templates = buildNucleotideTemplates ( in ) ; validate ( templates ) ; } catch ( IOException | JDOMException | NotationException e ) { throw new NucleotideLoadingException ( "Initializing NucleotideStore failed because of " + e . getClass ( ) . getSimpleName ( ) , e ) ; } logger . log ( Level . INFO , NUCLEOTIDE_TEMPLATE_XML_RESOURCE + " is used for nucleotide templates initialization" ) ; } nucleotideTemplates = templates ; reverseNucleotideMap = getReverseNucleotideTemplateMap ( NotationConstant . NOTATION_SOURCE ) ; }
This method is called during startup use local version if exist otherwise use XML version in jar
382
17
141,245
public void saveNucleotideTemplates ( ) throws IOException { File f = new File ( NOTATION_DIRECTORY ) ; if ( ! f . exists ( ) ) { f . mkdir ( ) ; } String nucleotideTemplatesXML = NucleotideParser . getNucleotideTemplatesXML ( getNucleotideTemplates ( ) ) ; FileOutputStream fos = new FileOutputStream ( LOCAL_NUCLEOTIDE_TEMPLATE_FILE_PATH ) ; fos . write ( nucleotideTemplatesXML . getBytes ( ) ) ; }
save Nucleotide Templates to disk file
127
9
141,246
@ SuppressWarnings ( "rawtypes" ) public Class [ ] getParamtersTypes ( ) { final Class [ ] types = new Class [ this . paramters . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { types [ i ] = this . paramters [ i ] . getClass ( ) ; } return types ; }
get the types of the parameters using java reflection .
80
10
141,247
private void readConfigFile ( ) { File configFile = new File ( CONFIG_FILE_PATH ) ; /* config file is not there -> create config file with default */ if ( ! configFile . exists ( ) ) { resetConfigToDefault ( ) ; } try { PropertiesConfiguration conf = new PropertiesConfiguration ( CONFIG_FILE_PATH ) ; chemistry = conf . getString ( CHEMISTRY_PLUGIN ) ; } catch ( ConfigurationException e ) { resetConfigToDefault ( ) ; e . printStackTrace ( ) ; } }
method to read the configuration file
114
6
141,248
public static boolean compileJavaClass ( String sourceCode ) { try { String fileName = getClassName ( sourceCode ) . concat ( ".java" ) ; logger . info ( "Compiling Java Class ({})" , fileName ) ; File rootDir = JKIOUtil . createTempDirectory ( ) ; String packageDir = getPackageDir ( sourceCode ) ; File sourceFile ; if ( packageDir != null ) { File file = new File ( rootDir , packageDir ) ; file . mkdirs ( ) ; sourceFile = new File ( file , fileName ) ; } else { sourceFile = new File ( rootDir , fileName ) ; } JKIOUtil . writeDataToFile ( sourceCode , sourceFile ) ; // Compile source file. JavaCompiler compiler = ToolProvider . getSystemJavaCompiler ( ) ; StandardJavaFileManager standardJavaFileManager = compiler . getStandardFileManager ( null , null , null ) ; standardJavaFileManager . setLocation ( StandardLocation . CLASS_PATH , getClassPath ( ) ) ; standardJavaFileManager . setLocation ( StandardLocation . SOURCE_PATH , Arrays . asList ( rootDir ) ) ; List < String > options = new ArrayList < String > ( ) ; options . add ( "-Xlint:unchecked" ) ; CompilationTask compilationTask = compiler . getTask ( null , standardJavaFileManager , null , options , null , standardJavaFileManager . getJavaFileObjectsFromFiles ( JK . toList ( sourceFile ) ) ) ; return compilationTask . call ( ) ; } catch ( IOException e ) { JK . throww ( e ) ; return false ; } // if (compiler.run(System.in, System.out, System.err, sourceFile.getPath()) != 0) { // JK.error("Compilation failed, check stack trace"); // } }
Compile java class .
405
5
141,249
@ Override public void showAndChoose ( IConsumer < File > consumer ) { this . consumer = consumer ; initSrvNodeFile ( ) ; Intent activityTreeIntent = new Intent ( activity , ActivityTreeChooser . class ) ; activityTreeIntent . putExtra ( FragmentNodes . ARG_ID_NODE_SRVNODES , new String [ ] { idFolderStart , idSrvGetNodeFile , idCommand , title } ) ; activity . startActivityForResult ( activityTreeIntent , REQUEST_NODE_FILE ) ; }
You must provide fileFilter idFolderStart and title to invoke it!
124
14
141,250
public static String getHELMNotationString ( Element rootElement ) { Element helmNotationElement = rootElement . getChild ( "HelmNotation" ) ; return helmNotationElement . getText ( ) ; }
Extracts the HELM string from the root node of the XHELM document
48
18
141,251
public static String getComplexNotationString ( Element rootElement ) { Element helmNotationElement = rootElement . getChild ( "HelmNotation" ) ; return helmNotationElement . getText ( ) ; }
Extracts the complex notation string from the root node of the XHELM document
47
18
141,252
public static MonomerStore getMonomerStore ( Element rootElement ) throws MonomerException , IOException { MonomerStore monomerStore = new MonomerStore ( ) ; Element monomerListElement = rootElement . getChild ( "Monomers" ) ; if ( monomerListElement != null ) { @ SuppressWarnings ( "unchecked" ) List < Element > elementList = monomerListElement . getChildren ( "Monomer" ) ; for ( Element monomerElement : elementList ) { Monomer m = MonomerParser . getMonomer ( monomerElement ) ; monomerStore . addMonomer ( m ) ; } } return monomerStore ; }
Generates the monomer store from a given XHELM document
149
14
141,253
public boolean isNumeric ( ) { final Class c = getColumnClass ( ) ; return c . equals ( Integer . class ) || c . equals ( Float . class ) || c . equals ( Long . class ) || c . equals ( BigDecimal . class ) ; }
Checks if is numeric .
58
6
141,254
public void setColumnClassName ( final String columnClassName ) throws ClassNotFoundException { if ( columnClassName . equals ( "byte[]" ) ) { setColumnClass ( Object . class ) ; } else { setColumnClass ( Class . forName ( columnClassName ) ) ; } this . columnClassName = columnClassName ; }
Sets the column class name .
73
7
141,255
public static String generateMDL ( final HELM2Notation helm2notation ) throws BuilderMoleculeException , CTKException , NotationException , ChemistryException { LOG . debug ( "Generate smiles representation for the whole HELM molecule" ) ; String smiles = SMILES . getSMILESForAll ( helm2notation ) ; LOG . debug ( "Convert smiles to mol" ) ; return Chemistry . getInstance ( ) . getManipulator ( ) . convert ( smiles , AbstractChemistryManipulator . StType . SMILES ) ; }
method to generate MDL for a HELM molecule
120
10
141,256
public void callMethod ( final MethodCallInfo info ) { this . logger . info ( "calling remote method " . concat ( info . toString ( ) ) ) ; try ( Socket socket = new Socket ( this . host , this . port ) ) { final ObjectOutputStream out = new ObjectOutputStream ( socket . getOutputStream ( ) ) ; out . writeObject ( info ) ; final ObjectInputStream in = new ObjectInputStream ( socket . getInputStream ( ) ) ; final MethodCallInfo serverCopy = ( MethodCallInfo ) in . readObject ( ) ; info . set ( serverCopy ) ; } catch ( final Exception e ) { throw new RemoteReflectionException ( e ) ; } }
Call the remote method based on the passed MethodCallInfo parameter .
149
13
141,257
protected static Vector convertToVector ( final Object [ ] anArray ) { if ( anArray == null ) { return null ; } final Vector v = new Vector ( anArray . length ) ; for ( final Object element : anArray ) { v . addElement ( element ) ; } return v ; }
Returns a vector that contains the same objects as the array .
63
12
141,258
private static Vector newVector ( final int size ) { final Vector v = new Vector ( size ) ; v . setSize ( size ) ; return v ; }
New vector .
33
3
141,259
@ Override public String getColumnName ( final int column ) { Object id = null ; // This test is to cover the case when // getColumnCount has been subclassed by mistake ... if ( column < this . columnIdentifiers . size ( ) && column >= 0 ) { id = this . columnIdentifiers . elementAt ( column ) ; } return id == null ? super . getColumnName ( column ) : id . toString ( ) ; }
Returns the column name .
95
5
141,260
private void justifyRows ( final int from , final int to ) { // Sometimes the DefaultTableModel is subclassed // instead of the AbstractTableModel by mistake. // Set the number of rows for the case when getRowCount // is overridden. this . dataVector . setSize ( getRowCount ( ) ) ; for ( int i = from ; i < to ; i ++ ) { if ( this . dataVector . elementAt ( i ) == null ) { this . dataVector . setElementAt ( new Vector ( ) , i ) ; } // ((Vector)dataVector.elementAt(i)).setSize(getColumnCount()); } }
Justify rows .
137
4
141,261
public static String findPathJar ( final Class clas ) throws IllegalStateException { URL url ; String extURL ; try { url = clas . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) ; } catch ( final SecurityException ex ) { url = clas . getResource ( clas . getSimpleName ( ) + ".class" ) ; } extURL = url . toExternalForm ( ) ; try { url = new URL ( extURL ) ; } catch ( final MalformedURLException mux ) { // leave url unchanged; probably does not happen } try { return new File ( url . toURI ( ) ) . toString ( ) ; } catch ( final Exception ex ) { return new File ( url . getPath ( ) ) . toString ( ) ; } }
If the provided class has been loaded from a jar file that is on the local file system will find the absolute path to that jar file .
173
28
141,262
public static byte [ ] readStream ( final InputStream inStream ) { try { return IOUtils . toByteArray ( inStream ) ; } catch ( IOException e ) { throw new JKException ( e ) ; } // // try { // DataInputStream in = null; // try { // in = new DataInputStream(inStream); // int ch; // // List<Byte> bytes=new ArrayList<>(); // while((ch=in.read())!=-1){ // bytes.add(ch); // } // return arr; // } finally { // if (in != null) { // in.close(); // } // } // } catch (final IOException e) { // throw new RuntimeException(e); // } }
Read stream .
161
3
141,263
public static String convertToString ( InputStream input ) throws IOException { try { if ( input == null ) { throw new IOException ( "Input Stream Cannot be NULL" ) ; } StringBuilder sb1 = new StringBuilder ( ) ; String line ; try { BufferedReader r1 = new BufferedReader ( new InputStreamReader ( input , "UTF-8" ) ) ; while ( ( line = r1 . readLine ( ) ) != null ) { sb1 . append ( line ) ; } } finally { input . close ( ) ; } return sb1 . toString ( ) ; } catch ( IOException e ) { throw new JKException ( e ) ; } }
Convert to string .
148
5
141,264
public static Reader getReader ( String name ) { InputStream inputStream = getInputStream ( name ) ; if ( inputStream != null ) { BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; return reader ; } return null ; }
Gets the reader .
58
5
141,265
public static String getExtension ( final String fileName , final boolean withPoint ) { final int lastIndexOf = fileName . lastIndexOf ( "." ) ; if ( ! withPoint ) { return fileName . substring ( lastIndexOf + 1 ) ; } return fileName . substring ( lastIndexOf ) ; }
Gets the extension .
70
5
141,266
public static String removeExtension ( String fileName ) { final String separator = FILE_SEPARATOR ; String filename ; // Remove the path upto the filename. final int lastSeparatorIndex = fileName . lastIndexOf ( separator ) ; if ( lastSeparatorIndex == - 1 ) { filename = fileName ; } else { filename = fileName . substring ( lastSeparatorIndex + 1 ) ; } // Remove the extension. final int extensionIndex = filename . lastIndexOf ( "." ) ; if ( extensionIndex == - 1 ) { return filename ; } fileName = fileName . substring ( 0 , lastSeparatorIndex ) ; return fileName + File . separator + filename . substring ( 0 , extensionIndex ) ; }
Removes the extension .
164
5
141,267
public static File writeDataToFile ( final byte [ ] data , final File file , final boolean append ) { try ( FileOutputStream out = new FileOutputStream ( file , append ) ) { out . write ( data ) ; out . flush ( ) ; out . close ( ) ; return file ; } catch ( Exception e ) { JKExceptionUtil . handle ( e ) ; return null ; } }
Write data to file .
86
5
141,268
public static Properties readPropertiesStream ( InputStream inputStream ) { try { final Properties prop = new Properties ( ) ; // try to read in utf 8 prop . load ( new InputStreamReader ( inputStream , Charset . forName ( "utf-8" ) ) ) ; JKCollectionUtil . fixPropertiesKeys ( prop ) ; return prop ; } catch ( IOException e ) { JKExceptionUtil . handle ( e ) ; return null ; } finally { close ( inputStream ) ; } }
Read properties stream .
111
4
141,269
public static File writeFileToTempDirectory ( final byte [ ] data , final String fileName ) { try { File file = createTempDirectory ( ) ; File out = new File ( file , fileName ) ; out . deleteOnExit ( ) ; file . deleteOnExit ( ) ; return writeDataToFile ( data , out ) ; } catch ( IOException e ) { JKExceptionUtil . handle ( e ) ; return null ; } }
Write file to temp directory .
95
6
141,270
public static File createTempFile ( final String ext ) { try { File file ; file = File . createTempFile ( "jk-" , "." + ext ) ; return file ; } catch ( IOException e ) { JK . throww ( e ) ; return null ; } }
Creates the temp file .
61
6
141,271
public static Process executeFile ( final String fileName ) { try { final String command = "cmd /c \"" + fileName + "\"" ; logger . info ( command ) ; return Runtime . getRuntime ( ) . exec ( command ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Execute file .
70
4
141,272
public static String getSqlFile ( String fileName ) { String file = "/jk/sql/" . concat ( fileName ) ; logger . debug ( "Loading sql file: " , file ) ; return readFile ( file ) ; }
Gets the sql file .
52
6
141,273
public static void clearTempFiles ( ) { String userFolderPath = getUserFolderPath ( false ) ; File file = new File ( userFolderPath ) ; deleteDir ( file ) ; }
Clear temp files .
40
4
141,274
public static void startFakeThread ( ServerSocket server ) { Thread thread = new Thread ( new FakeRunnable ( server ) ) ; thread . start ( ) ; }
Start fake thread .
35
4
141,275
public static String getReportsOutPath ( boolean appendFileSeprator ) { String userLocalPath = getUserFolderPath ( true ) ; String reportPath = userLocalPath + REPORTS_OUT_PATH ; checkFolderPath ( reportPath , true ) ; // to create the folder if not exist if ( appendFileSeprator ) { reportPath += FILE_SEPARATOR ; } return reportPath ; }
Gets the reports out path .
85
7
141,276
public static List < String > getFilesInFolder ( String folder , String ext ) { // tryto find using normal file system lookup List < String > files = new Vector <> ( ) ; File dir = new File ( folder ) ; if ( dir . exists ( ) && dir . isDirectory ( ) ) { String [ ] list = dir . list ( ) ; for ( String file : list ) { if ( file . endsWith ( ext ) ) { files . add ( file ) ; } } } return files ; }
Gets the files in folder .
109
7
141,277
public static void copResourcesFromJarToDir ( String sourceClassPath , File dest ) { try { List < File > resourcesInnPackage = getResourcesInnPackage ( sourceClassPath ) ; for ( File file : resourcesInnPackage ) { JK . printBlock ( "Copying file: " + file . getName ( ) + " to folder " + dest . getAbsolutePath ( ) ) ; FileUtils . copyFileToDirectory ( file , dest ) ; } } catch ( IOException e ) { JK . throww ( e ) ; } }
Cop resources from jar to dir .
121
7
141,278
public static List < File > getResourcesInnPackage ( String root ) { try { logger . debug ( "getResourcesInnPackage for package: " + root ) ; ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; URL url = loader . getResource ( root ) ; if ( url != null ) { logger . debug ( " URL :" + url . toURI ( ) ) ; InputStream in = loader . getResourceAsStream ( root ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( in ) ) ; String resource ; List < File > fileNames = new ArrayList <> ( ) ; while ( ( resource = br . readLine ( ) ) != null ) { if ( ! root . endsWith ( "/" ) ) { root += "/" ; } String resourcePath = root + resource ; logger . debug ( "Processing resource path:" + resourcePath ) ; File file = new File ( loader . getResource ( resourcePath ) . toURI ( ) ) ; if ( file . isDirectory ( ) ) { fileNames . addAll ( getResourcesInnPackage ( resourcePath + "/" ) ) ; } else { logger . debug ( "Adding file :" + file . getName ( ) ) ; fileNames . add ( file ) ; } } return fileNames ; } else { logger . debug ( "Package not found, return empty list" ) ; return Collections . emptyList ( ) ; } } catch ( Exception e ) { JK . throww ( e ) ; return null ; } }
Gets the resources inn package .
332
7
141,279
public static JKConfig readConfigFile ( String configFileName ) { URL url = getURL ( configFileName ) ; logger . debug ( configFileName + " Url is " , url . toString ( ) ) ; JKConfig config = new JKConfig ( url ) ; return config ; }
Read config file .
65
4
141,280
private static String convertLessThanOneThousand ( int number ) { String soFar ; if ( number % 100 < 20 ) { soFar = numNames [ number % 100 ] ; number /= 100 ; } else { soFar = numNames [ number % 10 ] ; number /= 10 ; soFar = tensNames [ number % 10 ] + soFar ; number /= 10 ; } if ( number == 0 ) { return soFar ; } return numNames [ number ] + " Hundred" + soFar ; }
Convert less than one thousand .
110
7
141,281
public static double addAmounts ( final double num1 , final double num2 ) { final BigDecimal b1 = new BigDecimal ( num1 ) ; final BigDecimal b2 = new BigDecimal ( num2 ) ; BigDecimal b3 = b1 . add ( b2 ) ; b3 = b3 . setScale ( 3 , BigDecimal . ROUND_HALF_UP ) ; final double result = b3 . doubleValue ( ) ; return result ; }
Adds the amounts .
106
4
141,282
public static double fixAmount ( final double value ) { final BigDecimal b1 = new BigDecimal ( value ) ; final BigDecimal b2 = b1 . setScale ( 3 , BigDecimal . ROUND_HALF_UP ) ; return b2 . doubleValue ( ) ; }
Fix amount .
65
3
141,283
public static double subAmounts ( final double n1 , final double n2 ) { final BigDecimal b1 = new BigDecimal ( n1 ) ; final BigDecimal b2 = new BigDecimal ( n2 ) ; BigDecimal b3 = b1 . subtract ( b2 ) ; b3 = b3 . setScale ( 3 , BigDecimal . ROUND_HALF_UP ) ; final double result = b3 . doubleValue ( ) ; return result ; }
Sub amounts .
106
3
141,284
public void fillEmail ( final MultiPartEmail email ) throws EmailException , IOException { email . setHostName ( getHost ( ) ) ; email . setSmtpPort ( getSmtpPort ( ) ) ; email . addTo ( getTo ( ) ) ; email . setFrom ( getFrom ( ) ) ; email . setSubject ( getSubject ( ) ) ; email . setMsg ( getMsg ( ) ) ; email . setSSLOnConnect ( isSecured ( ) ) ; if ( this . bcc != null ) { String [ ] bccList = this . bcc . split ( "," ) ; for ( String bcc : bccList ) { email . addBcc ( bcc ) ; } } if ( this . cc != null ) { String [ ] ccList = this . cc . split ( "," ) ; for ( String cc : ccList ) { email . addCc ( cc ) ; } } if ( isRequiresAuthentication ( ) ) { email . setAuthentication ( getUsername ( ) , getPassword ( ) ) ; } for ( int i = 0 ; i < this . attachements . size ( ) ; i ++ ) { final Attachment attachment = this . attachements . get ( i ) ; final ByteArrayDataSource ds = new ByteArrayDataSource ( attachment . getData ( ) , attachment . getMimeType ( ) ) ; email . attach ( ds , attachment . getName ( ) , attachment . getDescription ( ) ) ; } }
Fill email .
322
3
141,285
public static Date toDate ( final Object value ) { if ( value instanceof Date ) { return ( Date ) value ; } if ( value == null || value . equals ( "null" ) ) { return null ; } if ( value instanceof String ) { throw new IllegalStateException ( "fix me" ) ; } return null ; }
To date .
71
3
141,286
public static float toFloat ( final Object value ) { if ( value instanceof Float ) { return ( float ) value ; } if ( value == null ) { return 0 ; } return new Float ( value . toString ( ) ) ; }
To float .
50
3
141,287
public static java . sql . Time toTime ( final Object value ) { if ( value == null ) { return null ; } if ( value instanceof java . sql . Time ) { return ( java . sql . Time ) value ; } if ( value instanceof java . util . Date ) { final Date date = ( java . util . Date ) value ; return new java . sql . Time ( date . getTime ( ) ) ; } return null ; }
To time .
95
3
141,288
public static boolean toBoolean ( Object value , boolean defaultValue ) { boolean result ; // = defaultValue; if ( value != null ) { if ( value instanceof Boolean ) { return ( ( Boolean ) value ) . booleanValue ( ) ; } if ( value . toString ( ) . trim ( ) . equals ( "1" ) || value . toString ( ) . trim ( ) . toLowerCase ( ) . equals ( "true" ) ) { result = true ; } else { result = false ; } } else { result = defaultValue ; } return result ; }
To boolean .
122
3
141,289
public static double toDouble ( Object value , double defaultValue ) { if ( value == null || value . toString ( ) . trim ( ) . equals ( "" ) ) { return defaultValue ; } if ( value instanceof Double ) { return ( double ) value ; } if ( value instanceof Date ) { final Date date = ( Date ) value ; return date . getTime ( ) ; } return Double . parseDouble ( value . toString ( ) ) ; }
To double .
98
3
141,290
public static int toInteger ( Object value , int defaultValue ) { if ( value == null || value . toString ( ) . trim ( ) . equals ( "" ) ) { return defaultValue ; } if ( value instanceof Integer ) { return ( Integer ) value ; } return ( int ) JKConversionUtil . toDouble ( value ) ; }
To integer .
75
3
141,291
public static void validateNotationObjects ( HELM2Notation helm2notation ) throws PolymerIDsException , MonomerException , GroupingNotationException , ConnectionNotationException , NotationException , ChemistryException , MonomerLoadingException , org . helm . notation2 . parser . exceptionparser . NotationException { LOG . info ( "Validation process is starting" ) ; /* all polymer ids have to be unique */ if ( ! validateUniquePolymerIDs ( helm2notation ) ) { LOG . info ( "Polymer IDS have to be unique" ) ; throw new PolymerIDsException ( "Polymer IDs have to be unique" ) ; } /* Validation of Monomers */ if ( ! validateMonomers ( MethodsMonomerUtils . getListOfMonomerNotation ( helm2notation . getListOfPolymers ( ) ) ) ) { LOG . info ( "Monomers have to be valid" ) ; throw new MonomerException ( "Monomers have to be valid" ) ; } /* validate the grouping section */ if ( ! validateGrouping ( helm2notation ) ) { LOG . info ( "Group information is not valid" ) ; throw new GroupingNotationException ( "Group notation is not valid" ) ; } /* validate the connection */ if ( ! validateConnections ( helm2notation ) ) { LOG . info ( "Connection information is not valid" ) ; throw new ConnectionNotationException ( "Connection notation is not valid" ) ; } }
method to check if the generated notation objects by the parser are correct the polymer ids have to be unique ; all monomers have to be valid ; all used polymer ids in the grouping section have to be there ; all connections have to be valid
318
50
141,292
protected static boolean validateMonomers ( List < MonomerNotation > mon ) throws ChemistryException , MonomerLoadingException , org . helm . notation2 . parser . exceptionparser . NotationException { for ( MonomerNotation monomerNotation : mon ) { if ( ! ( isMonomerValid ( monomerNotation . getUnit ( ) , monomerNotation . getType ( ) ) ) ) { return false ; } } return true ; }
method to validate a list of MonomerNotation objects
98
11
141,293
private static boolean isConnectionSpecific ( ConnectionNotation connectionNotation ) { String connection = connectionNotation . getSourceUnit ( ) + ":" + connectionNotation . getrGroupSource ( ) + "-" + connectionNotation . getTargetUnit ( ) + ":" + connectionNotation . getrGroupTarget ( ) ; /* check for specific interaction */ if ( connection . matches ( "\\d+:R\\d-\\d+:R\\d|\\d+:pair-\\d+:pair" ) ) { return true ; } return false ; }
method to check if the given connection is specific
121
9
141,294
private static List < Integer > getOccurencesOfMonomerNotation ( String sourceUnit , HELMEntity e , HELM2Notation helm2notation ) throws org . helm . notation2 . parser . exceptionparser . NotationException , AttachmentException { List < Integer > occurences = new ArrayList < Integer > ( ) ; /* The monomer's position in the polymer is specified */ try { occurences . add ( Integer . parseInt ( sourceUnit ) ) ; return occurences ; } catch ( NumberFormatException ex ) { MonomerNotation mon = ValidationMethod . decideWhichMonomerNotation ( sourceUnit , e . getType ( ) ) ; /* it is only one monomer e.g. C */ if ( mon instanceof MonomerNotationUnit ) { PolymerNotation polymerNotation = helm2notation . getPolymerNotation ( e . getId ( ) ) ; /* monomer can also be unknown */ if ( sourceUnit . equals ( "?" ) ) { return occurences ; } occurences . addAll ( findElementInPolymer ( sourceUnit , polymerNotation ) ) ; /* the specified monomer does not exist in the polymer */ if ( occurences . isEmpty ( ) ) { throw new AttachmentException ( "Monomer is not there" ) ; } } /* second: group (mixture or or) or list */ else if ( mon instanceof MonomerNotationGroup || mon instanceof MonomerNotationList ) { PolymerNotation polymerNotation = helm2notation . getPolymerNotation ( e . getId ( ) ) ; Map < String , String > elements = new HashMap < String , String > ( ) ; for ( MonomerNotationGroupElement groupElement : ( ( MonomerNotationGroup ) mon ) . getListOfElements ( ) ) { elements . put ( groupElement . getMonomerNotation ( ) . getUnit ( ) , "" ) ; } for ( String e1 : elements . keySet ( ) ) { try { int i = Integer . parseInt ( e1 ) ; elements . put ( e1 , "1" ) ; occurences . add ( i ) ; } catch ( NumberFormatException ex1 ) { // have to be found in polymer List < Integer > foundMonomers = findElementInPolymer ( e1 , polymerNotation ) ; if ( foundMonomers . size ( ) > 0 ) { elements . put ( e1 , "1" ) ; occurences . addAll ( foundMonomers ) ; } } } if ( occurences . size ( ) < elements . size ( ) || elements . containsValue ( "" ) ) { throw new AttachmentException ( "Not all Monomers are there" ) ; } } return occurences ; } }
method to get all occurences of the MonomerNotation
605
13
141,295
public static boolean validateGrouping ( HELM2Notation helm2notation ) { List < GroupingNotation > listGroupings = helm2notation . getListOfGroupings ( ) ; List < String > listPolymerIDs = helm2notation . getPolymerAndGroupingIDs ( ) ; /* validate each group */ for ( GroupingNotation grouping : listGroupings ) { /* check for each group element if the polymer id is there */ for ( GroupingElement groupingElement : grouping . getAmbiguity ( ) . getListOfElements ( ) ) { if ( ! ( listPolymerIDs . contains ( groupingElement . getID ( ) . getId ( ) ) ) ) { LOG . info ( "Element of Group: " + groupingElement . getID ( ) . getId ( ) + " does not exist" ) ; return false ; } } } return true ; }
method to validate every GroupNotation of the Notation objects
188
12
141,296
public static boolean validateUniquePolymerIDs ( HELM2Notation helm2notation ) { List < String > listPolymerIDs = helm2notation . getPolymerAndGroupingIDs ( ) ; Map < String , String > uniqueId = new HashMap < String , String > ( ) ; for ( String polymerID : listPolymerIDs ) { uniqueId . put ( polymerID , "" ) ; } if ( listPolymerIDs . size ( ) > uniqueId . size ( ) ) { LOG . info ( "Polymer node IDs are not unique" ) ; return false ; } return true ; }
method to check if all existent polymer ids are unique
128
12
141,297
private static void checkExistenceOfPolymerID ( String str , List < String > listPolymerIDs ) throws PolymerIDsException { if ( ! ( listPolymerIDs . contains ( str ) ) ) { LOG . info ( "Polymer Id does not exist" ) ; throw new PolymerIDsException ( "Polymer ID does not exist" ) ; } }
method to check if the given polymer id exists in the given list of polymer ids
78
17
141,298
private static boolean isMonomerValid ( String str , String type ) throws ChemistryException , MonomerLoadingException , org . helm . notation2 . parser . exceptionparser . NotationException { LOG . info ( "Is Monomer valid: " + str ) ; MonomerFactory monomerFactory = null ; monomerFactory = MonomerFactory . getInstance ( ) ; /* Search in Database */ MonomerStore monomerStore = monomerFactory . getMonomerStore ( ) ; if ( monomerStore . hasMonomer ( type , str ) ) { LOG . info ( "Monomer is located in the database: " + str ) ; return true ; } else if ( str . charAt ( 0 ) == ' ' && str . charAt ( str . length ( ) - 1 ) == ' ' && monomerStore . hasMonomer ( type , str . substring ( 1 , str . length ( ) - 1 ) ) ) { LOG . info ( "Monomer is located in the database: " + str ) ; return true ; } /* polymer type is Blob: accept all */ else if ( type . equals ( "BLOB" ) ) { LOG . info ( "Blob's Monomer Type: " + str ) ; return true ; } /* new unknown monomer for peptide */ else if ( type . equals ( "PEPTIDE" ) && str . equals ( "X" ) ) { LOG . info ( "Unknown monomer type for peptide: " + str ) ; return true ; } /* new unknown monomer for peptide */ else if ( type . equals ( "RNA" ) && str . equals ( "N" ) ) { LOG . info ( "Unknown monomer type for rna: " + str ) ; return true ; } /* new unknown types */ else if ( str . equals ( "?" ) || str . equals ( "_" ) ) { LOG . info ( "Unknown types: " + str ) ; return true ; } /* nucleotide */ else if ( type . equals ( "RNA" ) ) { List < String > elements = NucleotideParser . getMonomerIDListFromNucleotide ( str ) ; for ( String element : elements ) { if ( ! ( monomerStore . hasMonomer ( type , element ) ) ) { /* SMILES Check */ if ( element . startsWith ( "[" ) && element . endsWith ( "]" ) ) { element = element . substring ( 1 , element . length ( ) - 1 ) ; } if ( ! Chemistry . getInstance ( ) . getManipulator ( ) . validateSMILES ( element ) ) { return false ; } } } LOG . info ( "Nucleotide type for RNA: " + str ) ; return true ; } LOG . info ( "SMILES Check" ) ; /* SMILES Check */ if ( str . charAt ( 0 ) == ' ' && str . charAt ( str . length ( ) - 1 ) == ' ' ) { str = str . substring ( 1 , str . length ( ) - 1 ) ; } return Chemistry . getInstance ( ) . getManipulator ( ) . validateSMILES ( str ) ; }
method to check the monomer s validation
681
8
141,299
private static void checkPolymerIDSConnection ( ConnectionNotation not , List < String > listPolymerIDs ) throws PolymerIDsException { /* the polymer ids have to be there */ checkExistenceOfPolymerID ( not . getSourceId ( ) . getId ( ) , listPolymerIDs ) ; checkExistenceOfPolymerID ( not . getTargetId ( ) . getId ( ) , listPolymerIDs ) ; }
method to check for one connection if the two polymer ids exist
94
13