signature:
public class InstallFeatureUtil { /** * Resolve , download , and install features from a Maven repository . This
 * method calls the resolver with the given JSONs and feature list ,
 * downloads the ESAs corresponding to the resolved features , then installs
 * those features .
 * @ param jsonRepos
 * JSON files , each containing an array of metadata for all
 * features in a Liberty release .
 * @ param featuresToInstall
 * The list of features to install .
 * @ throws PluginExecutionException
 * if any of the features could not be installed */
@ SuppressWarnings ( "unchecked" ) public void installFeatures ( boolean isAcceptLicense , List < String > featuresToInstall ) throws PluginExecutionException { } }

implementation:
List < File > jsonRepos = new ArrayList < File > ( downloadedJsons ) ; debug ( "JSON repos: " + jsonRepos ) ; info ( "Installing features: " + featuresToInstall ) ; // override license acceptance if installing only Open Liberty features
boolean acceptLicenseMapValue = isOnlyOpenLibertyFeatures ( featuresToInstall ) ? true : isAcceptLicense ; try { Map < String , Object > mapBasedInstallKernel = createMapBasedInstallKernelInstance ( installDirectory ) ; mapBasedInstallKernel . put ( "install.local.esa" , true ) ; mapBasedInstallKernel . put ( "single.json.file" , jsonRepos ) ; mapBasedInstallKernel . put ( "features.to.resolve" , featuresToInstall ) ; mapBasedInstallKernel . put ( "license.accept" , acceptLicenseMapValue ) ; if ( isDebugEnabled ( ) ) { mapBasedInstallKernel . put ( "debug" , Level . FINEST ) ; } Collection < ? > resolvedFeatures = ( Collection < ? > ) mapBasedInstallKernel . get ( "action.result" ) ; if ( resolvedFeatures == null ) { debug ( "action.exception.stacktrace: " + mapBasedInstallKernel . get ( "action.exception.stacktrace" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( "action.error.message" ) ; throw new PluginExecutionException ( exceptionMessage ) ; } else if ( resolvedFeatures . isEmpty ( ) ) { debug ( "action.exception.stacktrace: " + mapBasedInstallKernel . get ( "action.exception.stacktrace" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( "action.error.message" ) ; if ( exceptionMessage == null ) { debug ( "resolvedFeatures was empty but the install kernel did not issue any messages" ) ; info ( "The features are already installed, so no action is needed." ) ; return ; } else if ( exceptionMessage . contains ( "CWWKF1250I" ) ) { info ( exceptionMessage ) ; info ( "The features are already installed, so no action is needed." ) ; return ; } else { throw new PluginExecutionException ( exceptionMessage ) ; } } Collection < File > artifacts = downloadEsas ( resolvedFeatures ) ; StringBuilder installedFeaturesBuilder = new StringBuilder ( ) ; Collection < String > actionReturnResult = new ArrayList < String > ( ) ; for ( File esaFile : artifacts ) { mapBasedInstallKernel . put ( "license.accept" , acceptLicenseMapValue ) ; mapBasedInstallKernel . put ( "action.install" , esaFile ) ; if ( to != null ) { mapBasedInstallKernel . put ( "to.extension" , to ) ; debug ( "Installing to extension: " + to ) ; } Integer ac = ( Integer ) mapBasedInstallKernel . get ( "action.result" ) ; debug ( "action.result: " + ac ) ; debug ( "action.error.message: " + mapBasedInstallKernel . get ( "action.error.message" ) ) ; if ( mapBasedInstallKernel . get ( "action.error.message" ) != null ) { debug ( "action.exception.stacktrace: " + mapBasedInstallKernel . get ( "action.exception.stacktrace" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( "action.error.message" ) ; debug ( exceptionMessage ) ; throw new PluginExecutionException ( exceptionMessage ) ; } else if ( mapBasedInstallKernel . get ( "action.install.result" ) != null ) { actionReturnResult . addAll ( ( Collection < String > ) mapBasedInstallKernel . get ( "action.install.result" ) ) ; } } for ( String installResult : actionReturnResult ) { installedFeaturesBuilder . append ( installResult ) . append ( " " ) ; } productInfoValidate ( ) ; info ( "The following features have been installed: " + installedFeaturesBuilder . toString ( ) ) ; } catch ( PrivilegedActionException e ) { throw new PluginExecutionException ( "Could not load the jar " + installJarFile . getAbsolutePath ( ) , e ) ; }


signature:
public class InstallFeatureUtil { /** * Download the override bundle from the repository with the given groupId and
 * artifactId , corresponding to the latest version in the range between the
 * current Open Liberty version ( inclusive ) and the next version
 * ( exclusive ) . Returns a string in the format " filepath ; BundleName " where
 * BundleName is the bundle symbolic name from its manifest .
 * @ param groupId
 * the groupId of the bundle to download
 * @ param artifactId
 * the artifactId of the bundle to download
 * @ return a String representing the bundle in filepath ; BundleName format */
public String getOverrideBundleDescriptor ( String groupId , String artifactId ) throws PluginExecutionException { } }

implementation: File overrideJar = downloadOverrideJar ( groupId , artifactId ) ; if ( overrideJar != null && overrideJar . exists ( ) ) { String symbolicName = extractSymbolicName ( overrideJar ) ; if ( symbolicName != null ) { return overrideJar . getAbsolutePath ( ) + ";" + symbolicName ; } } return null ;


signature:
public class InstallFeatureUtil { /** * Gets the next product version number .
 * @ param version
 * the product version
 * @ return the String representation of the next product version */
public static String getNextProductVersion ( String version ) throws PluginExecutionException { } }

implementation: String result = null ; int versionSplittingIndex = version . lastIndexOf ( "." ) + 1 ; if ( versionSplittingIndex == 0 ) { throw new PluginExecutionException ( "Product version " + version + " is not in the expected format. It must have period separated version segments." ) ; } String quarterVersion = version . substring ( versionSplittingIndex ) ; int nextQuarterSpecifier ; try { nextQuarterSpecifier = Integer . parseInt ( quarterVersion ) + 1 ; } catch ( NumberFormatException e ) { throw new PluginExecutionException ( "Product version " + version + " is not in the expected format. Its last segment is expected to be an integer." , e ) ; } result = version . substring ( 0 , versionSplittingIndex ) + nextQuarterSpecifier ; return result ;


signature:
public class InstallFeatureUtil { /** * Extracts the bundle symbolic name from the jar manifest .
 * @ param jar
 * the jar from which the symbolic name will be extracted
 * @ return the Bundle - SymbolicName */
public static String extractSymbolicName ( File jar ) throws PluginExecutionException { } }

implementation:
JarFile jarFile = null ; try { jarFile = new JarFile ( jar ) ; return jarFile . getManifest ( ) . getMainAttributes ( ) . getValue ( "Bundle-SymbolicName" ) ; } catch ( IOException e ) { throw new PluginExecutionException ( "Could not load the jar " + jar . getAbsolutePath ( ) , e ) ; } finally { if ( jarFile != null ) { try { jarFile . close ( ) ; } catch ( IOException e ) { // nothing to do here
} } }


signature:
public class InstallFeatureUtil { /** * Find latest install map jar from specified directory
 * @ return the install map jar file */
public static File getMapBasedInstallKernelJar ( File dir ) { } }

implementation: File [ ] installMapJars = dir . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File dir , String name ) { return name . startsWith ( INSTALL_MAP_PREFIX ) && name . endsWith ( INSTALL_MAP_SUFFIX ) ; } } ) ; File result = null ; if ( installMapJars != null ) { for ( File jar : installMapJars ) { if ( isReplacementJar ( result , jar ) ) { result = jar ; } } } return result ;


signature:
public class InstallFeatureUtil { /** * Returns whether file2 can replace file1 as the install map jar .
 * @ param file1
 * @ param file2
 * @ return true if file2 is a replacement jar for file1 false otherwise */
private static boolean isReplacementJar ( File file1 , File file2 ) { } }

implementation: if ( file1 == null ) { return true ; } else if ( file2 == null ) { return false ; } else { String version1 = extractVersion ( file1 . getName ( ) ) ; String version2 = extractVersion ( file2 . getName ( ) ) ; return compare ( version1 , version2 ) < 0 ; }


signature:
public class InstallFeatureUtil { /** * Returns the extracted version from fileName
 * @ param fileName
 * @ return the version extracted from fileName */
private static String extractVersion ( String fileName ) { } }

implementation:
int startIndex = INSTALL_MAP_PREFIX . length ( ) + 1 ; // skip the underscore after the prefix
int endIndex = fileName . lastIndexOf ( INSTALL_MAP_SUFFIX ) ; if ( startIndex < endIndex ) { return fileName . substring ( startIndex , endIndex ) ; } else { return null ; }


signature:
public class InstallFeatureUtil { /** * Performs pairwise comparison of version strings , including nulls and non - integer components .
 * @ param version1
 * @ param version2
 * @ return positive if version1 is greater , negative if version2 is greater , otherwise 0 */
private static int compare ( String version1 , String version2 ) { } }

implementation: if ( version1 == null && version2 == null ) { return 0 ; } else if ( version1 == null && version2 != null ) { return - 1 ; } else if ( version1 != null && version2 == null ) { return 1 ; } String [ ] components1 = version1 . split ( "\\." ) ; String [ ] components2 = version2 . split ( "\\." ) ; for ( int i = 0 ; i < components1 . length && i < components2 . length ; i ++ ) { int comparison ; try { comparison = new Integer ( components1 [ i ] ) . compareTo ( new Integer ( components2 [ i ] ) ) ; } catch ( NumberFormatException e ) { comparison = components1 [ i ] . compareTo ( components2 [ i ] ) ; } if ( comparison != 0 ) { return comparison ; } } return components1 . length - components2 . length ;


signature:
public class InstallFeatureUtil { /** * Performs product validation by running bin / productInfo validate
 * @ throws PluginExecutionException
 * if product validation failed or could not be run */
private void productInfoValidate ( ) throws PluginExecutionException { } }

implementation: String output = productInfo ( installDirectory , "validate" ) ; if ( output == null ) { throw new PluginExecutionException ( "Could not perform product validation. The productInfo command returned with no output" ) ; } else if ( output . contains ( "[ERROR]" ) ) { throw new PluginExecutionException ( output ) ; } else { info ( "Product validation completed successfully." ) ; }


signature:
public class InstallFeatureUtil { /** * Runs the productInfo command and returns the output
 * @ param installDirectory The directory of the installed runtime
 * @ param action The action to perform for the productInfo command
 * @ return The command output
 * @ throws PluginExecutionException if the exit value of the command was not 0 */
public static String productInfo ( File installDirectory , String action ) throws PluginExecutionException { } }

implementation:
Process pr = null ; InputStream is = null ; Scanner s = null ; Worker worker = null ; try { String command ; if ( OSUtil . isWindows ( ) ) { command = installDirectory + "\\bin\\productInfo.bat " + action ; } else { command = installDirectory + "/bin/productInfo " + action ; } pr = Runtime . getRuntime ( ) . exec ( command ) ; worker = new Worker ( pr ) ; worker . start ( ) ; worker . join ( 300000 ) ; if ( worker . exit == null ) { throw new PluginExecutionException ( "productInfo command timed out" ) ; } int exitValue = pr . exitValue ( ) ; if ( exitValue != 0 ) { throw new PluginExecutionException ( "productInfo exited with return code " + exitValue ) ; } is = pr . getInputStream ( ) ; s = new Scanner ( is ) ; // use regex to match the beginning of the input
s . useDelimiter ( "\\A" ) ; if ( s . hasNext ( ) ) { return s . next ( ) ; } return null ; } catch ( IOException ex ) { throw new PluginExecutionException ( "productInfo error: " + ex ) ; } catch ( InterruptedException ex ) { worker . interrupt ( ) ; Thread . currentThread ( ) . interrupt ( ) ; throw new PluginExecutionException ( "productInfo error: " + ex ) ; } finally { if ( s != null ) { s . close ( ) ; } if ( is != null ) { try { is . close ( ) ; } catch ( IOException e ) { } } if ( pr != null ) { pr . destroy ( ) ; } }


signature:
public class SpringBootUtil { /** * Check whether the given artifact is a Spring Boot Uber JAR
 * @ param artifact
 * @ return true if so , false otherwise */
public static boolean isSpringBootUberJar ( File artifact ) { } }

implementation:
if ( artifact == null || ! artifact . exists ( ) || ! artifact . isFile ( ) ) { return false ; } try ( JarFile jarFile = new JarFile ( artifact ) ) { Manifest manifest = jarFile . getManifest ( ) ; if ( manifest != null ) { Attributes attributes = manifest . getMainAttributes ( ) ; if ( attributes . getValue ( BOOT_VERSION_ATTRIBUTE ) != null && attributes . getValue ( BOOT_START_CLASS_ATTRIBUTE ) != null ) { return true ; } else { // Checking that there is a spring - boot - VERSION . RELEASE . jar in the BOOT - INF / lib directory
// Handles the Gradle case where the spring plugin does not set the properties in the manifest
Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; String entryName = entry . getName ( ) ; if ( ! entryName . startsWith ( "org" ) && ( entryName . matches ( BOOT_JAR_EXPRESSION ) || entryName . matches ( BOOT_WAR_EXPRESSION ) ) ) { return true ; } } } } } catch ( IOException e ) { } return false ;


signature:
public class LibertyProperty { /** * Converts Map < String , String > to Map < LibertyPropertyI , String > . Validates
 * each key property name .
 * @ param arquillianProperties
 * @ return a map of converted arquillianProperties
 * @ throws ArquillianConfigurationException
 * if a property name is invalid . */
public static Map < LibertyPropertyI , String > getArquillianProperties ( Map < String , String > arquillianProperties , Class < ? > cls ) throws ArquillianConfigurationException { } }

implementation: Map < LibertyPropertyI , String > props = new HashMap < LibertyPropertyI , String > ( ) ; if ( arquillianProperties != null && ! arquillianProperties . isEmpty ( ) ) { for ( Entry < String , String > entry : arquillianProperties . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( key != null && value != null ) { LibertyPropertyI p = getArquillianProperty ( key , cls ) ; props . put ( p , value ) ; } } } return props ;


signature:
public class LibertyProperty { /** * Check that the given key exists in ArquillianProperties
 * @ param key
 * @ return true if so , fail the build otherwise
 * @ throws MojoFailureException */
private static LibertyPropertyI getArquillianProperty ( String key , Class < ? > cls ) throws ArquillianConfigurationException { } }

implementation: try { if ( cls == LibertyManagedObject . LibertyManagedProperty . class ) { return LibertyManagedObject . LibertyManagedProperty . valueOf ( key ) ; } else if ( cls == LibertyRemoteObject . LibertyRemoteProperty . class ) { return LibertyRemoteObject . LibertyRemoteProperty . valueOf ( key ) ; } } catch ( IllegalArgumentException e ) { throw new ArquillianConfigurationException ( "Property \"" + key + "\" in arquillianProperties does not exist. You probably have a typo." ) ; } throw new ArquillianConfigurationException ( "This should never happen." ) ;


signature:
public class ImageWebReporter { /** * We assume any environment that is not headless will have a web browser to display the image in a web page . */
@ Override public boolean isWorkingInThisEnvironment ( String forFile ) { } }

implementation: return ! GraphicsEnvironment . isHeadless ( ) && GenericDiffReporter . isFileExtensionValid ( forFile , GenericDiffReporter . IMAGE_FILE_EXTENSIONS ) ;


signature:
public class FancyMessageBox { /** * Prints a request for a text input to the window . < br >
 * < b > Example : < / b >
 * { @ code String name = FancyMessageBox . askForTextInput ( " What is your nickname ? " , " Nicknames " ) ; }
 * @ param message
 * the text in the FancyMessageBox
 * @ param title
 * the title of the FancyMessageBox
 * @ return the user input as a string */
public static String askForTextInput ( String message , String title ) { } }

implementation: return fancyMessageBox . askForTextInput ( message , title ) ;


signature:
public class FancyMessageBox { /** * Prints the message to the window . < br >
 * < b > Example : < / b > { @ code FancyMessageBox . showMessage ( " Girl programmers rule ! " , " Just the Facts " ) ; }
 * @ param message
 * the text in the FancyMessageBox
 * @ param title
 * the title of the FancyMessageBox
 * @ param icon
 * a file and path that has an image for the MessageBox */
public static void showMesage ( String message , String title , ImageIcon icon ) { } }

implementation: fancyMessageBox . showMessage ( message , title , icon ) ;


signature:
public class Parser { /** * Parses a file
 * < div > < b > Example : < / b > { @ code parser . parseRtfFile ( filename , data ) } < / div >
 * @ param fileName A filename for the new file , built from the template view . rtf
 * @ param data A data object to put into the template fields .
 * @ return the completed template */
public static String parseRtfFile ( String fileName , Object data ) { } }

implementation: try { String text = FileUtils . readFromClassPath ( data . getClass ( ) , fileName ) ; return parse ( text , "\\{" , "\\}" , data ) ; } catch ( Exception e ) { throw ObjectUtils . throwAsError ( e ) ; }


signature:
public class Circle { /** * Paints a circle
 * < div > < b > Example : < / b > { @ code circle . paint ( g , caller ) } < / div >
 * @ param g
 * the graphics object
 * @ param caller
 * the Program Window or panel */
@ Override public void paint ( Graphics2D g , JPanel caller ) { } }

implementation: Color color2 = PenColors . getTransparentVersion ( mainColor , percentTransparent ) ; g . setColor ( color2 ) ; g . fillOval ( x - radius , y - radius , radius * 2 , radius * 2 ) ;


signature:
public class Tortoise { /** * Makes a cool shape fast
 * < div > < b > Example : < / b > { @ code tortoise . drawShape ( 6 , PenColors . Reds . Red , 50 , 20 ) } < / div >
 * @ param sides
 * the number of sides
 * @ param color
 * a snazzy line color
 * @ param length
 * the bigger the better
 * @ param width
 * make a thick line - it ' s cool */
public static void drawShape ( int sides , Color color , int length , int width ) { } }

implementation: Tortoise . show ( ) ; Tortoise . setSpeed ( 7 ) ; Tortoise . getBackgroundWindow ( ) . getCanvas ( ) . setBackground ( PenColors . Yellows . Goldenrod ) ; new Text ( "TKP Java - Make Some Shapes!" ) . setTopLeft ( 225 , 50 ) . addTo ( Tortoise . getBackgroundWindow ( ) ) ; for ( int i = 0 ; i < sides ; i ++ ) { Tortoise . setPenColor ( color ) ; Tortoise . setPenWidth ( width ) ; Tortoise . move ( length ) ; Tortoise . turn ( 360 / sides ) ; } VirtualProctor . setClassName ( "Grace Hopper's Class" ) ; VirtualProctor . setName ( "Jean Bartik" ) ;


signature:
public class Tortoise { /** * Draws an entire Tortoise - - fast !
 * < div > < b > Example : < / b > { @ code tortoise . drawTortoise ( ) } < / div > */
public static void drawTortoise ( ) { } }

implementation: Tortoise . show ( ) ; Tortoise . setSpeed ( 9 ) ; Tortoise . getBackgroundWindow ( ) . setBackground ( PenColors . Greens . DarkSeaGreen ) ; new Text ( "TKP Java - It's the Tortoise!" ) . setTopLeft ( 200 , 75 ) . addTo ( Tortoise . getBackgroundWindow ( ) ) ; Tortoise . setPenColor ( PenColors . Greens . Green ) ; Tortoise . setPenWidth ( 3 ) ; makeTortoiseBody ( ) ; Tortoise . setPenColor ( PenColors . Browns . Brown ) ; Tortoise . turn ( - 65 ) ; Tortoise . makeTortoiseLeg ( ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 150 ) ; Tortoise . turn ( - 90 ) ; Tortoise . makeTortoiseLeg ( ) ;


signature:
public class Tortoise { /** * Checks if a tortoise can eat a slice of a pizza
 * < div > < b > Example : < / b > { @ code tortoise . eatPizza ( pizza ) } < / div >
 * @ param pizza
 * the pizza
 * @ return whether or not there is pizza left to eat that a tortoise likes */
public boolean eatPizza ( Pizza pizza ) { } }

implementation: if ( ! pizza . takeSlice ( ) ) { return false ; } if ( this . topping == null ) { return true ; } if ( this . topping != Topping . Cheese ) { return pizza . hasTopping ( topping ) ; } return pizza . wasCooked ( ) && pizza . hasTopping ( topping ) ;


signature:
public class RecursiveSquare { /** * Create the makeASquare recipe - - # 11.1 */
private static void makeASquare ( double length ) { } }

implementation:
// If the current length is greater than 10 - - # 10.2
if ( length > 10 ) { // Run the recipe moveToTheSquareStart with the current length - - # 4.3
moveToTheSquareStart ( length ) ; // Do the following 4 times - - # 7.1
for ( int i = 0 ; i < 4 ; i ++ ) { // Move the Tortoise the current length
Tortoise . move ( length ) ; // MakeASquare with the current length divided by 1.7 ( recipe below ) - - # 11.3
makeASquare ( length / 1.7 ) ; // If the current process count is less than 3 ( HINT : use ' i ' ) - - # 9
if ( i < 3 ) { // Turn the tortoise 90 degrees to the right
Tortoise . turn ( 90 ) ; } // End Repeat - - # 7.2
} // MoveBackToCenter with the current length ( recipe below ) - - # 5.3
moveBackToCenter ( length ) ; // Set the current length to the current length times two - - # 10.1
length = length * 2 ; } // End of makeASquare recipe


signature:
public class RecursiveSquare { /** * Create the moveToTheSquareStart recipe - - # 4.1 */
private static void moveToTheSquareStart ( double length ) { } }

implementation:
// Set the pen up for the tortoise - - # 1.2
Tortoise . setPenUp ( ) ; // Move the tortoise the current length divided by two - - # 1.3
Tortoise . move ( length / 2 ) ; // Turn the tortoise 90 degrees to the left - - # 2.1
Tortoise . turn ( - 90 ) ; // Move the tortoise the current length divided by two - - # 2.2
Tortoise . move ( length / 2 ) ; // Turn the tortoise 180 degrees to the right - - # 3.1
Tortoise . turn ( 180 ) ; // Set the pen down for the tortoise - - # 3.2
Tortoise . setPenDown ( ) ; // End of moveToTheSquareStart recipe - - # 4.2


signature:
public class RecursiveSquare { /** * Create the moveBackToCenter recipe */
private static void moveBackToCenter ( double length ) { } }

implementation: Tortoise . setPenUp ( ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( length / 2 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( length / 2 ) ; Tortoise . turn ( 180 ) ; Tortoise . setPenDown ( ) ;


signature:
public class ObjectUtils { /** * A convenience function to check if two objects are equal .
 * @ param s1
 * The first object
 * @ param s2
 * The second object
 * @ return true if Equal . */
public static boolean isEqual ( Object s1 , Object s2 ) { } }

implementation: return s1 == s2 || ( s1 != null ) && s1 . equals ( s2 ) ;


signature:
public class Viewer { /** * Uses a RTF Viewer to display the results of a model ( or text )
 * < div > < b > Example : < / b > { @ code viewer . displayRtfFile ( text ) } < / div >
 * @ param text
 * A model created from a String ( text ) */
public static void displayRtfFile ( String text ) { } }

implementation: try { File file ; file = File . createTempFile ( "currentStory" , ".rtf" ) ; FileWriter f = new FileWriter ( file ) ; f . write ( text ) ; f . close ( ) ; TestUtils . displayFile ( file . getPath ( ) ) ; } catch ( IOException e ) { throw ObjectUtils . throwAsError ( e ) ; }


signature:
public class NumberUtils { /** * Loads an int from a String .
 * @ param i a string with an integer in it
 * @ param defaultValue value to use when no integer can be found in the string
 * @ param stripNonNumeric true if non - numeric characters should be removed from the string
 * @ return the integer found in the string */
public static int load ( String i , int defaultValue , boolean stripNonNumeric ) { } }

implementation: try { i = stripNonNumeric ? StringUtils . stripNonNumeric ( i , true , true ) : i ; defaultValue = Integer . parseInt ( i ) ; } catch ( Exception ignored ) { } return defaultValue ;


signature:
public class NumberUtils { /** * randomly chooses a number between the minimum and maximum
 * < div > < b > Example : < / b >
 * { @ code int grade = NumberUtils . getRandomInt ( 1,100 ) ; } < / div >
 * @ param minimum The lowest possible value ( inclusive )
 * @ param maximum The highest possible value ( inclusive )
 * @ return the random number */
public static int getRandomInt ( int minimum , int maximum ) { } }

implementation: int diff = maximum - minimum ; if ( diff == 0 ) { return maximum ; } else { return RANDOM . nextInt ( diff ) + minimum ; }


signature:
public class DeepDive07Objects { /** * Ignore the following , It ' s needed to run the deep dive */
private Tortoise [ ] throwPizzaParty ( ) { } }

implementation: Tortoise karai = new Tortoise ( ) ; Tortoise cecil = new Tortoise ( ) ; Tortoise michealangelo = new Tortoise ( ) ; Tortoise fred = new Tortoise ( ) ; return new Tortoise [ ] { karai , cecil , michealangelo , fred } ;


signature:
public class Pizza { /** * Checks to see if a pizza has a particular kind of topping
 * < div > < b > Example : < / b > { @ code pizza . hasTopping ( topping ) } < / div >
 * @ param topping A topping from the list to check for
 * @ return < b > true < / b > when the pizza has the topping on it */
public boolean hasTopping ( Topping topping ) { } }

implementation: for ( Topping toppingToday : toppings ) { if ( toppingToday == topping ) { return true ; } } return false ;


signature: public class SimpleFileFilter { public boolean accept ( File pathname ) { } }

implementation: String name = pathname . getName ( ) . toLowerCase ( ) ; boolean accept ; accept = ! ( name . equals ( "." ) || name . equals ( ".." ) ) && ! pathname . isDirectory ( ) ; return accept ;


signature:
public class DigiFlower { /** * - - - - - Recipe for CreateColorPalette - - # 8.2 */
private static void createColorPalette ( ) { } }

implementation: Color color1 = PenColors . Reds . Red ; Color color2 = PenColors . Oranges . DarkOrange ; Color color3 = PenColors . Yellows . Gold ; Color color4 = PenColors . Yellows . Yellow ; ColorWheel . addColor ( color1 ) ; ColorWheel . addColor ( color2 ) ; ColorWheel . addColor ( color3 ) ; ColorWheel . addColor ( color4 ) ; ColorWheel . addColor ( color4 ) ; ColorWheel . addColor ( color3 ) ; ColorWheel . addColor ( color2 ) ; ColorWheel . addColor ( color1 ) ; // - - - - - End of createColorPalette recipe - - # 8.3


signature:
public class DigiFlower { /** * - - - - - Recipe for DrawOctogon - - # 9.2 */
private static void drawOctogon ( ) { } }

implementation:
// Do the following 8 times - - # 5.1
for ( int i = 0 ; i < 8 ; i ++ ) { // Change the pen color of the line the tortoise draws to the next color on the color wheel - - # 3
Tortoise . setPenColor ( ColorWheel . getNextColor ( ) ) ; // Move the tortoise 50 pixels - - # 2
Tortoise . move ( 50 ) ; // Turn the tortoise 1/8th of 360 degrees to the right - - # 4
Tortoise . turn ( 360.0 / 8 ) ; // End Repeat - - # 5.2
} // - - - - - End of drawOctogon recipe - - # 10.3


signature:
public class TortoiseUtils { /** * Captures an image of the result of your program and displays it to you */
public static void verify ( ) { } }

implementation: try { Approvals . verify ( TURTLE . getImage ( ) ) ; } catch ( Exception e ) { throw ObjectUtils . throwAsError ( e ) ; } finally { TortoiseUtils . resetTurtle ( ) ; }


signature:
public class Puzzle { /** * Calculate the < a href = " http : / / en . wikipedia . org / wiki / Taxicab _ geometry " > Manhattan Distance < / a > between two positions .
 * @ param start
 * The starting position .
 * @ param end
 * The ending position .
 * @ return The distance between the two positions . */
public static int getDistance ( Point start , Point end ) { } }

implementation: return Math . abs ( start . x - end . x ) + Math . abs ( start . y - end . y ) ;


signature:
public class Puzzle { /** * Create a copy of the puzzle where the blank swapped with the value in the target position
 * @ param target
 * move the blank to this location , and move the value from this location to the current blank location
 * @ return A copy of the puzzle with the blank and target swapped . */
public Puzzle swapBlank ( int target ) { } }

implementation: int [ ] copy = Arrays . copyOf ( cells , cells . length ) ; int x = copy [ target ] ; copy [ getBlankIndex ( ) ] = x ; copy [ target ] = 8 ; return new Puzzle ( copy ) ;


signature:
public class Puzzle { /** * Calculate the distance between the goal by summing the distance between each cell and its goal .
 * @ return The distance to the goal . */
public int getDistanceToGoal ( ) { } }

implementation: int distance = 0 ; for ( int i = 0 ; i < cells . length ; i ++ ) { distance += getDistance ( i , cells [ i ] ) ; } return distance ;


signature:
public class Sound { /** * Sets a sound that you can play through your speakers .
 * Use a TKPSound ( there is a list ) < br >
 * < b > Example : < / b > { @ code Sound . setSound ( TKPSound . Ahem ) } */
public synchronized void setSound ( TKPSound mySound ) { } }

implementation: String sound = "soundFiles/" + mySound + ".wav" ; URL resource = this . getClass ( ) . getResource ( sound ) ; if ( resource == null ) { resource = this . getClass ( ) . getClassLoader ( ) . getResource ( sound ) ; } if ( resource == null ) { throw new IllegalStateException ( "Could not get TKPSound: " + sound ) ; } this . soundUrl = resource ;


signature:
public class Sound { /** * Plays a TKPSound through your speakers .
 * You must first set the TKPSound < br >
 * < b > Example : < / b > { @ code Sound . playSound ( ) } */
public synchronized void playSound ( ) { } }

implementation: final URL sound = this . soundUrl ; new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { Clip clip = AudioSystem . getClip ( ) ; AudioInputStream inputStream = AudioSystem . getAudioInputStream ( sound ) ; clip . open ( inputStream ) ; clip . start ( ) ; } catch ( Exception e ) { System . out . println ( "play sound error: " + e . getMessage ( ) + " for " + sound ) ; } } } ) . start ( ) ;


signature:
public class StdOut { /** * Prints a formatted string to standard output , using the specified format
 * string and arguments , and then flushes standard output .
 * @ param format the < a href = " http : / / docs . oracle . com / javase / 7 / docs / api / java / util / Formatter . html # syntax " > format string < / a >
 * @ param args the arguments accompanying the format string */
public static void printf ( String format , Object ... args ) { } }

implementation: out . printf ( LOCALE , format , args ) ; out . flush ( ) ;


signature:
public class StdOut { /** * Prints a formatted string to standard output , using the locale and
 * the specified format string and arguments ; then flushes standard output .
 * @ param locale the locale
 * @ param format the < a href = " http : / / docs . oracle . com / javase / 7 / docs / api / java / util / Formatter . html # syntax " > format string < / a >
 * @ param args the arguments accompanying the format string */
public static void printf ( Locale locale , String format , Object ... args ) { } }

implementation: out . printf ( locale , format , args ) ; out . flush ( ) ;


signature:
public class StdOut { /** * Unit tests some of the methods in < tt > StdOut < / tt > . */
public static void main ( String [ ] args ) { } }

implementation:
// write to stdout
StdOut . println ( "Test" ) ; StdOut . println ( 17 ) ; StdOut . println ( true ) ; StdOut . printf ( "%.6f\n" , 1.0 / 7.0 ) ;


signature:
public class WhichFish { /** * recipe for makeAFishyDecision with the numberOfFish */
public static void makeAFishyDecision ( int numberOfFish ) { } }

implementation:
// Use a switch . . . case on the numberOfFish
switch ( numberOfFish ) { // When the numberOfFish is - 1
case - 1 : // Uncomment to create a string of this image
String image = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/thumb-up.png" ; // Create a new ImageIcon from your image
ImageIcon icon = new ImageIcon ( image ) ; // Show a message with the fancy message box this text , this title and this icon . . .
FancyMessageBox . showMesage ( "Had a Fish" , "Not hungry anymore..." , icon ) ; // End
break ; // When the numberOfFish is 0
case 0 : // Uncomment to create a string of this image
String image0 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/information.png" ; // Create a new ImageIcon from your image
ImageIcon icon0 = new ImageIcon ( image0 ) ; // Show a message with the fancy message box this text , this title and this icon . . .
FancyMessageBox . showMesage ( "No Fish" , "Still hungry" , icon0 ) ; // End
break ; // When the numberOfFish is 1
case 1 : // Uncomment to create a string of this image
String image1 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/star.png" ; // Create a new ImageIcon from your image
ImageIcon icon1 = new ImageIcon ( image1 ) ; // Show a message with the fancy message box this text , this title and this icon . . .
FancyMessageBox . showMesage ( "One Fish" , "This one has a little star" , icon1 ) ; // End
break ; // When the numberOfFish is 0
case 2 : // Uncomment to create a string of this image
String image2 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/github.png" ; // Create a new ImageIcon from your image
ImageIcon icon2 = new ImageIcon ( image2 ) ; // Show a message with the fancy message box this text , this title and this icon . . .
FancyMessageBox . showMesage ( "Two Fish" , "Funny things are everywhere" , icon2 ) ; // End
break ; // Otherwise
default : // Uncomment to create a string of this image
String image4 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/hint.png" ; // Create a new ImageIcon from your image
ImageIcon icon4 = new ImageIcon ( image4 ) ; // Show a message with the fancy message box this text , this title and this icon . . .
FancyMessageBox . showMesage ( "Vegetaraian meal" , "Fish are icky" , icon4 ) ; // End
break ; }


signature:
public class StdDraw { /** * Draws a line segment between ( < em > x < / em > < sub > 0 < / sub > , < em > y < / em > < sub > 0 < / sub > ) and
 * ( < em > x < / em > < sub > 1 < / sub > , < em > y < / em > < sub > 1 < / sub > ) .
 * @ param x0 the < em > x < / em > - coordinate of one endpoint
 * @ param y0 the < em > y < / em > - coordinate of one endpoint
 * @ param x1 the < em > x < / em > - coordinate of the other endpoint
 * @ param y1 the < em > y < / em > - coordinate of the other endpoint */
public static void line ( double x0 , double y0 , double x1 , double y1 ) { } }

implementation: offscreen . draw ( new Line2D . Double ( scaleX ( x0 ) , scaleY ( y0 ) , scaleX ( x1 ) , scaleY ( y1 ) ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws one pixel at ( < em > x < / em > , < em > y < / em > ) .
 * This method is private because pixels depend on the display .
 * To achieve the same effect , set the pen radius to 0 and call { @ code point ( ) } .
 * @ param x the < em > x < / em > - coordinate of the pixel
 * @ param y the < em > y < / em > - coordinate of the pixel */
private static void pixel ( double x , double y ) { } }

implementation: offscreen . fillRect ( ( int ) Math . round ( scaleX ( x ) ) , ( int ) Math . round ( scaleY ( y ) ) , 1 , 1 ) ;


signature:
public class StdDraw { /** * Draws a point centered at ( < em > x < / em > , < em > y < / em > ) .
 * The point is a filled circle whose radius is equal to the pen radius .
 * To draw a single - pixel point , first set the pen radius to 0.
 * @ param x the < em > x < / em > - coordinate of the point
 * @ param y the < em > y < / em > - coordinate of the point */
public static void point ( double x , double y ) { } }

implementation: double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double r = currentPenRadius ; float scaledPenRadius = ( float ) ( r * DEFAULT_SIZE ) ; if ( scaledPenRadius <= 1 ) pixel ( x , y ) ; else offscreen . fill ( new Ellipse2D . Double ( xs - scaledPenRadius / 2 , ys - scaledPenRadius / 2 , scaledPenRadius , scaledPenRadius ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws a circle of the specified radius , centered at ( < em > x < / em > , < em > y < / em > ) .
 * @ param x the < em > x < / em > - coordinate of the center of the circle
 * @ param y the < em > y < / em > - coordinate of the center of the circle
 * @ param radius the radius of the circle
 * @ throws IllegalArgumentException if { @ code radius } is negative */
public static void circle ( double x , double y , double radius ) { } }

implementation: if ( ! ( radius >= 0 ) ) throw new IllegalArgumentException ( "radius must be nonnegative" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * radius ) ; double hs = factorY ( 2 * radius ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Ellipse2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws an ellipse with the specified semimajor and semiminor axes ,
 * centered at ( < em > x < / em > , < em > y < / em > ) .
 * @ param x the < em > x < / em > - coordinate of the center of the ellipse
 * @ param y the < em > y < / em > - coordinate of the center of the ellipse
 * @ param semiMajorAxis is the semimajor axis of the ellipse
 * @ param semiMinorAxis is the semiminor axis of the ellipse
 * @ throws IllegalArgumentException if either { @ code semiMajorAxis }
 * or { @ code semiMinorAxis } is negative */
public static void ellipse ( double x , double y , double semiMajorAxis , double semiMinorAxis ) { } }

implementation: if ( ! ( semiMajorAxis >= 0 ) ) throw new IllegalArgumentException ( "ellipse semimajor axis must be nonnegative" ) ; if ( ! ( semiMinorAxis >= 0 ) ) throw new IllegalArgumentException ( "ellipse semiminor axis must be nonnegative" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * semiMajorAxis ) ; double hs = factorY ( 2 * semiMinorAxis ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Ellipse2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws a circular arc of the specified radius ,
 * centered at ( < em > x < / em > , < em > y < / em > ) , from angle1 to angle2 ( in degrees ) .
 * @ param x the < em > x < / em > - coordinate of the center of the circle
 * @ param y the < em > y < / em > - coordinate of the center of the circle
 * @ param radius the radius of the circle
 * @ param angle1 the starting angle . 0 would mean an arc beginning at 3 o ' clock .
 * @ param angle2 the angle at the end of the arc . For example , if
 * you want a 90 degree arc , then angle2 should be angle1 + 90.
 * @ throws IllegalArgumentException if { @ code radius } is negative */
public static void arc ( double x , double y , double radius , double angle1 , double angle2 ) { } }

implementation: if ( radius < 0 ) throw new IllegalArgumentException ( "arc radius must be nonnegative" ) ; while ( angle2 < angle1 ) angle2 += 360 ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * radius ) ; double hs = factorY ( 2 * radius ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Arc2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs , angle1 , angle2 - angle1 , Arc2D . OPEN ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws a square of side length 2r , centered at ( < em > x < / em > , < em > y < / em > ) .
 * @ param x the < em > x < / em > - coordinate of the center of the square
 * @ param y the < em > y < / em > - coordinate of the center of the square
 * @ param halfLength one half the length of any side of the square
 * @ throws IllegalArgumentException if { @ code halfLength } is negative */
public static void square ( double x , double y , double halfLength ) { } }

implementation: if ( ! ( halfLength >= 0 ) ) throw new IllegalArgumentException ( "half length must be nonnegative" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * halfLength ) ; double hs = factorY ( 2 * halfLength ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Rectangle2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws a rectangle of the specified size , centered at ( < em > x < / em > , < em > y < / em > ) .
 * @ param x the < em > x < / em > - coordinate of the center of the rectangle
 * @ param y the < em > y < / em > - coordinate of the center of the rectangle
 * @ param halfWidth one half the width of the rectangle
 * @ param halfHeight one half the height of the rectangle
 * @ throws IllegalArgumentException if either { @ code halfWidth } or { @ code halfHeight } is negative */
public static void rectangle ( double x , double y , double halfWidth , double halfHeight ) { } }

implementation: if ( ! ( halfWidth >= 0 ) ) throw new IllegalArgumentException ( "half width must be nonnegative" ) ; if ( ! ( halfHeight >= 0 ) ) throw new IllegalArgumentException ( "half height must be nonnegative" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * halfWidth ) ; double hs = factorY ( 2 * halfHeight ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Rectangle2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws a polygon with the vertices
 * ( < em > x < / em > < sub > 0 < / sub > , < em > y < / em > < sub > 0 < / sub > ) ,
 * ( < em > x < / em > < sub > 1 < / sub > , < em > y < / em > < sub > 1 < / sub > ) , . . . ,
 * ( < em > x < / em > < sub > < em > n < / em > & minus ; 1 < / sub > , < em > y < / em > < sub > < em > n < / em > & minus ; 1 < / sub > ) .
 * @ param x an array of all the < em > x < / em > - coordinates of the polygon
 * @ param y an array of all the < em > y < / em > - coordinates of the polygon
 * @ throws IllegalArgumentException unless { @ code x [ ] } and { @ code y [ ] }
 * are of the same length */
public static void polygon ( double [ ] x , double [ ] y ) { } }

implementation: if ( x == null ) throw new NullPointerException ( ) ; if ( y == null ) throw new NullPointerException ( ) ; int n1 = x . length ; int n2 = y . length ; if ( n1 != n2 ) throw new IllegalArgumentException ( "arrays must be of the same length" ) ; int n = n1 ; GeneralPath path = new GeneralPath ( ) ; path . moveTo ( ( float ) scaleX ( x [ 0 ] ) , ( float ) scaleY ( y [ 0 ] ) ) ; for ( int i = 0 ; i < n ; i ++ ) path . lineTo ( ( float ) scaleX ( x [ i ] ) , ( float ) scaleY ( y [ i ] ) ) ; path . closePath ( ) ; offscreen . draw ( path ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws the specified image centered at ( < em > x < / em > , < em > y < / em > ) .
 * The supported image formats are JPEG , PNG , and GIF .
 * As an optimization , the picture is cached , so there is no performance
 * penalty for redrawing the same image multiple times ( e . g . , in an animation ) .
 * However , if you change the picture file after drawing it , subsequent
 * calls will draw the original picture .
 * @ param x the center < em > x < / em > - coordinate of the image
 * @ param y the center < em > y < / em > - coordinate of the image
 * @ param filename the name of the image / picture , e . g . , " ball . gif "
 * @ throws IllegalArgumentException if the image filename is invalid */
public static void picture ( double x , double y , String filename ) { } }

implementation: Image image = getImageFromFile ( filename ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; int ws = image . getWidth ( null ) ; int hs = image . getHeight ( null ) ; if ( ws < 0 || hs < 0 ) throw new IllegalArgumentException ( "image " + filename + " is corrupt" ) ; offscreen . drawImage ( image , ( int ) Math . round ( xs - ws / 2.0 ) , ( int ) Math . round ( ys - hs / 2.0 ) , null ) ; draw ( ) ;


signature:
public class StdDraw { /** * Draws the specified image centered at ( < em > x < / em > , < em > y < / em > ) , rotated
 * given number of degrees , and rescaled to the specified bounding box .
 * The supported image formats are JPEG , PNG , and GIF .
 * @ param x the center < em > x < / em > - coordinate of the image
 * @ param y the center < em > y < / em > - coordinate of the image
 * @ param filename the name of the image / picture , e . g . , " ball . gif "
 * @ param scaledWidth the width of the scaled image in pixels
 * @ param scaledHeight the height of the scaled image in pixels
 * @ param degrees is the number of degrees to rotate counterclockwise
 * @ throws IllegalArgumentException if either { @ code scaledWidth }
 * or { @ code scaledHeight } is negative
 * @ throws IllegalArgumentException if the image filename is invalid */
public static void picture ( double x , double y , String filename , double scaledWidth , double scaledHeight , double degrees ) { } }

implementation: if ( scaledWidth < 0 ) throw new IllegalArgumentException ( "width is negative: " + scaledWidth ) ; if ( scaledHeight < 0 ) throw new IllegalArgumentException ( "height is negative: " + scaledHeight ) ; Image image = getImageFromFile ( filename ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( scaledWidth ) ; double hs = factorY ( scaledHeight ) ; if ( ws < 0 || hs < 0 ) throw new IllegalArgumentException ( "image " + filename + " is corrupt" ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; offscreen . rotate ( Math . toRadians ( - degrees ) , xs , ys ) ; offscreen . drawImage ( image , ( int ) Math . round ( xs - ws / 2.0 ) , ( int ) Math . round ( ys - hs / 2.0 ) , ( int ) Math . round ( ws ) , ( int ) Math . round ( hs ) , null ) ; offscreen . rotate ( Math . toRadians ( + degrees ) , xs , ys ) ; draw ( ) ;


signature:
public class StdDraw { /** * Write the given text string in the current font , centered at ( < em > x < / em > , < em > y < / em > ) .
 * @ param x the center < em > x < / em > - coordinate of the text
 * @ param y the center < em > y < / em > - coordinate of the text
 * @ param text the text to write */
public static void text ( double x , double y , String text ) { } }

implementation: if ( text == null ) throw new NullPointerException ( ) ; offscreen . setFont ( font ) ; FontMetrics metrics = offscreen . getFontMetrics ( ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; int ws = metrics . stringWidth ( text ) ; int hs = metrics . getDescent ( ) ; offscreen . drawString ( text , ( float ) ( xs - ws / 2.0 ) , ( float ) ( ys + hs ) ) ; draw ( ) ;


signature:
public class StdDraw { /** * Write the given text string in the current font , centered at ( < em > x < / em > , < em > y < / em > ) and
 * rotated by the specified number of degrees .
 * @ param x the center < em > x < / em > - coordinate of the text
 * @ param y the center < em > y < / em > - coordinate of the text
 * @ param text the text to write
 * @ param degrees is the number of degrees to rotate counterclockwise */
public static void text ( double x , double y , String text , double degrees ) { } }

implementation: if ( text == null ) throw new NullPointerException ( ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; offscreen . rotate ( Math . toRadians ( - degrees ) , xs , ys ) ; text ( x , y , text ) ; offscreen . rotate ( Math . toRadians ( + degrees ) , xs , ys ) ;


signature:
public class StdDraw { /** * Saves the drawing to using the specified filename .
 * The supported image formats are JPEG and PNG ;
 * the filename suffix must be < tt > . jpg < / tt > or < tt > . png < / tt > .
 * @ param filename the name of the file with one of the required suffixes */
public static void save ( String filename ) { } }

implementation: if ( filename == null ) throw new NullPointerException ( ) ; File file = new File ( filename ) ; String suffix = filename . substring ( filename . lastIndexOf ( '.' ) + 1 ) ; if ( suffix . toLowerCase ( ) . equals ( "png" ) ) { try { ImageIO . write ( onscreenImage , suffix , file ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else if ( suffix . toLowerCase ( ) . equals ( "jpg" ) ) { WritableRaster raster = onscreenImage . getRaster ( ) ; WritableRaster newRaster ; newRaster = raster . createWritableChild ( 0 , 0 , width , height , 0 , 0 , new int [ ] { 0 , 1 , 2 } ) ; DirectColorModel cm = ( DirectColorModel ) onscreenImage . getColorModel ( ) ; DirectColorModel newCM = new DirectColorModel ( cm . getPixelSize ( ) , cm . getRedMask ( ) , cm . getGreenMask ( ) , cm . getBlueMask ( ) ) ; BufferedImage rgbBuffer = new BufferedImage ( newCM , newRaster , false , null ) ; try { ImageIO . write ( rgbBuffer , suffix , file ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else { System . out . println ( "Invalid image file type: " + suffix ) ; }


signature:
public class MySystem { /** * Prints to screen any variable information to be viewed .
 * @ param name The value ' s name
 * @ param value The value to print */
public synchronized static void variable ( String name , Object value ) { } }

implementation: if ( ! variable ) { return ; } System . out . println ( timeStamp ( ) + "*=> " + name + " = '" + ( value == null ? null : value . toString ( ) ) + "'" ) ;


signature:
public class TortoiseMaze { /** * / * setup code */
private void setUpTortoise ( ) { } }

implementation:
Tortoise . show ( ) ; Tortoise . setSpeed ( 10 ) ; Tortoise . setPenColor ( PenColors . Greens . Green ) ; Tortoise . setPenWidth ( 4 ) ; // TODO : Generate a unique maze png and set as background for this maze instance
// call tortoiseMaze . setupBackground


signature:
public class TKPLogo { /** * Sets up a particular set of Colors on the Color Wheel
 * < div > < b > Example : < / b > { @ code TKPLogo . setupColorWheel ( ) ; } < / div > */
public static void setupColorWheel ( ) { } }

implementation: ColorWheel . addColor ( PenColors . Grays . Gray ) ; ColorWheel . addColor ( PenColors . Greens . Green ) ; ColorWheel . addColor ( PenColors . Pinks . Pink ) ; ColorWheel . addColor ( PenColors . Purples . Purple ) ; ColorWheel . addColor ( PenColors . Blues . Blue ) ; ColorWheel . addColor ( PenColors . Yellows . Yellow ) ; ColorWheel . addColor ( PenColors . Browns . Brown ) ; ColorWheel . addColor ( PenColors . Oranges . Orange ) ; ColorWheel . addColor ( PenColors . Reds . Red ) ; ColorWheel . addColor ( PenColors . Whites . White ) ; setupBackgroundAndLines ( ) ;


signature:
public class TKPLogo { /** * Draws an < i > amazing < / > TKP inner P
 * < div > < b > Example : < / b > { @ code TKPLogo . draw _ inner _ tkp _ P ( ) ; } < / div > */
public static void draw_inner_tkp_P ( ) { } }

implementation: Tortoise . setX ( MakeALogo . XValue + 355 ) ; Tortoise . setY ( MakeALogo . YValue - 135 ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 10 ) ; TKPLogo . curve6 ( ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 50 ) ; Tortoise . hide ( ) ; Tortoise . turn ( 1 ) ;


signature:
public class TKPLogo { /** * Draws an < i > awesome < / > TKP outer P
 * < div > < b > Example : < / b > { @ code TKPLogo . draw _ outer _ tkp _ P ( ) ; } < / div > */
public static void draw_outer_tkp_P ( ) { } }

implementation: Tortoise . setAngle ( 180 ) ; Tortoise . setX ( MakeALogo . XValue + 320 ) ; Tortoise . setY ( MakeALogo . YValue ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 120 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 47 ) ; TKPLogo . curve5 ( ) ; Tortoise . move ( 12 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 50 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 43 ) ;


signature:
public class TKPLogo { /** * Draws an < i > outstanding < / > TKP right bracket
 * < div > < b > Example : < / b > { @ code TKPLogo . drawRightBracket ( ) ; } < / div > */
public static void drawRightBracket ( ) { } }

implementation: Tortoise . setAngle ( - 90 ) ; Tortoise . setX ( MakeALogo . XValue + 250 ) ; Tortoise . setY ( MakeALogo . YValue - 20 ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 30 ) ; TKPLogo . curve3 ( ) ; Tortoise . move ( 40 ) ; TKPLogo . curve4 ( ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 10 ) ; TKPLogo . curve4 ( ) ; Tortoise . move ( 40 ) ; TKPLogo . curve3 ( ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 15 ) ; TKPLogo . curve1 ( ) ; Tortoise . move ( 35 ) ; TKPLogo . curve2 ( ) ; Tortoise . turn ( 180 ) ; TKPLogo . curve2 ( ) ; Tortoise . move ( 35 ) ; TKPLogo . curve1 ( ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 11 ) ;


signature:
public class TKPLogo { /** * Draws an < i > incredible < / > TKP T
 * < div > < b > Example : < / b > { @ code TKPLogo . draw _ tkp _ T ( ) ; } < / div > */
public static void draw_tkp_T ( ) { } }

implementation: Tortoise . setX ( MakeALogo . XValue ) ; Tortoise . setY ( MakeALogo . YValue ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 120 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( - 75 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 75 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 35 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 95 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 35 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 75 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 75 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 120 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 50 ) ;


signature:
public class TKPLogo { /** * Draws an < i > impressive < / > TKP K
 * < div > < b > Example : < / b > { @ code TKPLogo . draw _ tkp _ K ( ) ; } < / div > */
public static void draw_tkp_K ( ) { } }

implementation: Tortoise . setAngle ( 180 ) ; Tortoise . setX ( MakeALogo . XValue + 150 ) ; Tortoise . setY ( MakeALogo . YValue + 15 ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 200 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 128 ) ; Tortoise . turn ( - 150 ) ; Tortoise . move ( 70 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 70 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 80 ) ; Tortoise . turn ( 140 ) ; Tortoise . move ( 40 ) ; Tortoise . turn ( 40 ) ; Tortoise . move ( 60 ) ; Tortoise . turn ( - 130 ) ; Tortoise . move ( 45 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( 2 ) ;


signature:
public class MultiTurtleWindow { /** * Adds a turtle instance to a window
 * NOTE : this method must be called BEFORE calling any other methods on turtle instances
 * < p > < b > Example : < / b > { @ code multiTurtleWindow . addTurtle ( myTurtle ) } < / p >
 * @ param turtle
 * A turtle instance */
public void addTurtle ( Turtle turtle ) { } }

implementation: if ( turtle == null ) { return ; } turtle . setFrame ( this . getFrame ( ) ) ; turtle . setPanel ( this ) ; this . turtles . add ( turtle ) ; clearPainters ( ) ; configurePainters ( ) ;


signature:
public class PentagonCrazy { /** * - - - - - Recipe for CreateColorPalette ( HINT : Use PenColors ) - - # 8 */
private static void createColorPalette ( ) { } }

implementation:
// Add steel blue to the color wheel - - # 7
ColorWheel . addColor ( PenColors . Blues . SteelBlue ) ; // Add dark orchid to the color wheel - - # 11
ColorWheel . addColor ( PenColors . Purples . DarkOrchid ) ; // Add dark slate blue to the color wheel - - # 12
ColorWheel . addColor ( PenColors . Blues . DarkSlateBlue ) ; // Add teal to the color wheel - - # 13
ColorWheel . addColor ( PenColors . Blues . Teal ) ; // Add indigo to the color wheel - - # 14
ColorWheel . addColor ( PenColors . Purples . Indigo ) ;


signature:
public class PentagonCrazy { /** * - - - - - Recipe for AdjustPen - - # 9 */
private static void adjustPen ( ) { } }

implementation:
// Change the color of the line the tortoise draws to the next color on the color wheel - - # 6
Tortoise . setPenColor ( ColorWheel . getNextColor ( ) ) ; // Increase the tortoises pen width by 1 - - # 15
Tortoise . setPenWidth ( Tortoise . getPenWidth ( ) + 1.0 ) ; // If the tortoise ' s pen width is greater than 4 , then - - # 17
if ( Tortoise . getPenWidth ( ) > 4 ) { // Reset the pen width to 1 - - # 16
Tortoise . setPenWidth ( 1 ) ; }


signature:
public class PentagonCrazy { /** * - - - - - Recipe for DrawPentagon - - # 10 */
private static void drawPentagon ( ) { } }

implementation:
// Do the following 200 times - - # 2
for ( int i = 0 ; i < 200 ; i ++ ) { // AdjustPen ( recipe below ) - - # 9
adjustPen ( ) ; // Move the tortoise the length of a side - - # 4
Tortoise . move ( i ) ; // Turn the tortoise 1/5th of 360 degrees - - # 1
Tortoise . turn ( 360.0 / 5 ) ; // Turn the tortoise 1 more degree - - # 5
Tortoise . turn ( 1 ) ; }


signature:
public class Turtle { /** * Sets the speed that a turtle instance moves
 * < p > < b > Example : < / b > { @ code myTurtle . setSpeed ( speed ) } < / p >
 * @ param speed
 * The speed from 1 ( slowest ) to 10 ( fastest ) */
public void setSpeed ( int speed ) { } }

implementation: if ( speed != TEST_SPEED ) { if ( speed < 1 || 10 < speed ) { throw new RuntimeException ( String . format ( "I call shenanigans!!!\nThe speed '%s' is not between the acceptable range of [1-10]\nPerhaps you should read the documentation" , speed ) ) ; } } this . speed = speed ;


signature:
public class Turtle { /** * Sets the distance that a turtle instance moves in pixels
 * < p > < b > Example : < / b > { @ code myTurtle . move ( 100 ) } < / p >
 * @ param amount
 * The distance that your turtle moves in pixels . Negative numbers will move your turtle backwards */
public void move ( Number amount ) { } }

implementation: double max = MAX_MOVE_AMOUNT ; Saver < Double > s = penDown ? new Mover ( new Point ( getX ( ) , getY ( ) ) ) : new EmptyMover ( ) ; animate ( amount . doubleValue ( ) , max , s ) ;


signature:
public class Turtle { /** * Draws a lightning bolt of a specified length
 * < p > < b > Example : < / b > { @ code myTurtle . drawLightning ( length ) } < / p >
 * @ param length
 * The length of a lightning bolt */
public void drawLightning ( int length ) { } }

implementation: this . setX ( 50 ) ; this . setY ( 350 ) ; this . setSpeed ( 10 ) ; for ( int i = 1 ; i < 5 ; i ++ ) { this . setPenWidth ( i * 4 ) ; this . turn ( 65 + i ) ; this . move ( length ) ; this . turn ( - 65 ) ; this . move ( length ) ; }


signature:
public class Diamond { /** * Paints a diamond
 * < div > < b > Example : < / b > { @ code diamond . paint ( g , caller ) } < / div >
 * @ param g
 * the graphics object
 * @ param caller
 * the Program Window or panel */
@ Override public void paint ( Graphics2D g , JPanel caller ) { } }

implementation: Color color2 = PenColors . getTransparentVersion ( mainColor , percentTransparent ) ; g . setColor ( color2 ) ; int width = 400 ; int height = 300 ; g . rotate ( 50 ) ; g . fillRect ( x , y , width , height ) ;


signature:
public class SpiderWeb { /** * - - - - - Recipe for WeaveOneLayer - - # 9 */
public static double weaveOneLayer ( double length , double zoom ) { } }

implementation:
// Do the following 6 times - - # 5
for ( int i = 0 ; i < 6 ; i ++ ) { // DrawTriangle ( recipe below ) - - # 4.2
drawTriangle ( length ) ; // Turn the tortoise 1/6th of 360 degrees to the right - - # 7
Tortoise . turn ( 360.0 / 6 ) ; // Increase the length of the line by the current zoom - - # 8.1
length += zoom ; // End Repeat - - # 10.2
} return length ;


signature:
public class SpiderWeb { /** * - - - - - Recipe for DrawTriangle - - # 4 */
public static void drawTriangle ( double length ) { } }

implementation:
// Do the following 3 times - - # 3.1
for ( int i = 0 ; i < 3 ; i ++ ) { // Move the tortoise the length of a line - - # 1.1
Tortoise . move ( length ) ; // Turn the tortoise 1/3rd of 360 degrees - - # 2
Tortoise . turn ( 360.0 / 3 ) ; // End Repeat - - # 3.2
}


signature:
public class StdRandom { /** * Returns a random integer uniformly in [ a , b ) .
 * @ param a the left endpoint
 * @ param b the right endpoint
 * @ return a random integer uniformly in [ a , b )
 * @ throws IllegalArgumentException if < tt > b < = a < / tt >
 * @ throws IllegalArgumentException if < tt > b - a > = Integer . MAX _ VALUE < / tt > */
public static int uniform ( int a , int b ) { } }

implementation: if ( b <= a ) throw new IllegalArgumentException ( "Invalid range" ) ; if ( ( long ) b - a >= Integer . MAX_VALUE ) throw new IllegalArgumentException ( "Invalid range" ) ; return a + uniform ( b - a ) ;


signature:
public class StdRandom { /** * Returns a random real number uniformly in [ a , b ) .
 * @ param a the left endpoint
 * @ param b the right endpoint
 * @ return a random real number uniformly in [ a , b )
 * @ throws IllegalArgumentException unless < tt > a < b < / tt > */
public static double uniform ( double a , double b ) { } }

implementation: if ( ! ( a < b ) ) throw new IllegalArgumentException ( "Invalid range" ) ; return a + uniform ( ) * ( b - a ) ;


signature:
public class StdRandom { /** * Returns a random integer from a geometric distribution with success
 * probability < em > p < / em > .
 * @ param p the parameter of the geometric distribution
 * @ return a random integer from a geometric distribution with success
 * probability < tt > p < / tt >
 * @ throws IllegalArgumentException unless < tt > p > = 0.0 < / tt > and < tt > p < = 1.0 < / tt > */
public static int geometric ( double p ) { } }

implementation:
if ( ! ( p >= 0.0 && p <= 1.0 ) ) throw new IllegalArgumentException ( "Probability must be between 0.0 and 1.0" ) ; // using algorithm given by Knuth
return ( int ) Math . ceil ( Math . log ( uniform ( ) ) / Math . log ( 1.0 - p ) ) ;


signature:
public class StdRandom { /** * Returns a random integer from a Poisson distribution with mean & lambda ; .
 * @ param lambda the mean of the Poisson distribution
 * @ return a random integer from a Poisson distribution with mean < tt > lambda < / tt >
 * @ throws IllegalArgumentException unless < tt > lambda > 0.0 < / tt > and not infinite */
public static int poisson ( double lambda ) { } }

implementation:
if ( ! ( lambda > 0.0 ) ) throw new IllegalArgumentException ( "Parameter lambda must be positive" ) ; if ( Double . isInfinite ( lambda ) ) throw new IllegalArgumentException ( "Parameter lambda must not be infinite" ) ; // using algorithm given by Knuth
// see http : / / en . wikipedia . org / wiki / Poisson _ distribution
int k = 0 ; double p = 1.0 ; double L = Math . exp ( - lambda ) ; do { k ++ ; p *= uniform ( ) ; } while ( p >= L ) ; return k - 1 ;


signature:
public class StdRandom { /** * Returns a random integer from the specified discrete distribution .
 * @ param a the probability of occurrence of each integer
 * @ return a random integer from a discrete distribution :
 * < tt > i < / tt > with probability < tt > a [ i ] < / tt >
 * @ throws NullPointerException if < tt > a < / tt > is < tt > null < / tt >
 * @ throws IllegalArgumentException if sum of array entries is not ( very nearly ) equal to < tt > 1.0 < / tt >
 * @ throws IllegalArgumentException unless < tt > a [ i ] > = 0.0 < / tt > for each index < tt > i < / tt > */
public static int discrete ( double [ ] a ) { } }

implementation:
if ( a == null ) throw new NullPointerException ( "argument array is null" ) ; double EPSILON = 1E-14 ; double sum = 0.0 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( ! ( a [ i ] >= 0.0 ) ) throw new IllegalArgumentException ( "array entry " + i + " must be nonnegative: " + a [ i ] ) ; sum = sum + a [ i ] ; } if ( sum > 1.0 + EPSILON || sum < 1.0 - EPSILON ) throw new IllegalArgumentException ( "sum of array entries does not approximately equal 1.0: " + sum ) ; // the for loop may not return a value when both r is ( nearly ) 1.0 and when the
// cumulative sum is less than 1.0 ( as a result of floating - point roundoff error )
while ( true ) { double r = uniform ( ) ; sum = 0.0 ; for ( int i = 0 ; i < a . length ; i ++ ) { sum = sum + a [ i ] ; if ( sum > r ) return i ; } }


signature:
public class StdRandom { /** * Unit test . */
public static void main ( String [ ] args ) { } }

implementation: int N = Integer . parseInt ( args [ 0 ] ) ; if ( args . length == 2 ) StdRandom . setSeed ( Long . parseLong ( args [ 1 ] ) ) ; double [ ] t = { .5 , .3 , .1 , .1 } ; StdOut . println ( "seed = " + StdRandom . getSeed ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { StdOut . printf ( "%2d " , uniform ( 100 ) ) ; StdOut . printf ( "%8.5f " , uniform ( 10.0 , 99.0 ) ) ; StdOut . printf ( "%5b " , bernoulli ( .5 ) ) ; StdOut . printf ( "%7.5f " , gaussian ( 9.0 , .2 ) ) ; StdOut . printf ( "%2d " , discrete ( t ) ) ; StdOut . println ( ) ; } String [ ] a = "A B C D E F G" . split ( " " ) ; for ( String s : a ) StdOut . print ( s + " " ) ; StdOut . println ( ) ;


signature:
public class HttpAsset { /** * Sets http http according to path .
 * It must exist as http .
 * @ param path */
public void setAsset ( String path ) { } }

implementation: try { this . asset = new URL ( path ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( "URL does not exist: " + path ) ; }


signature:
public class HttpAsset { /** * Loads http from the http
 * @ return */
private byte [ ] loadAssetFromURL ( ) { } }

implementation: try { URLConnection cnn = this . asset . openConnection ( ) ; cnn . connect ( ) ; int b = - 1 ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; while ( ( b = cnn . getInputStream ( ) . read ( ) ) != - 1 ) stream . write ( b ) ; stream . flush ( ) ; stream . close ( ) ; this . lastModified = cnn . getLastModified ( ) ; this . expireAt = cnn . getExpiration ( ) ; this . ETAG = cnn . getHeaderField ( HttpHeaders . ETAG ) ; return stream . toByteArray ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; }


signature:
public class Strings { /** * Capitalizes the first character of the word given .
 * It will convert i to I
 * @ param word
 * @ return result */
public static final String capitalizeFirstChar ( String word ) { } }

implementation: return Character . toUpperCase ( word . charAt ( 0 ) ) + word . substring ( 1 ) ;


signature:
public class Strings { /** * Un capitalizes the first character of the word given .
 * It will convert i to I
 * @ param word
 * @ return result */
public static final String unCapitalizeFirstChar ( String word ) { } }

implementation: return Character . toLowerCase ( word . charAt ( 0 ) ) + word . substring ( 1 ) ;


signature:
public class UserResource { /** * Create as a { @ link User } resource .
 * @ param credentials injected by { @ link RobeAuth } annotation for authentication .
 * @ param model data of { @ link User }
 * @ return Create as a { @ link User } resource . */
@ RobeService ( group = "User" , description = "Create as a User resource." ) @ POST @ UnitOfWork public User create ( @ RobeAuth Credentials credentials , @ Valid User model ) { } }

implementation: return userDao . create ( model ) ;


signature:
public class UserResource { /** * Updates a single { @ link User } matches with the given id .
 * Status Code :
 * Not Found 404
 * Not Matches 412
 * @ param credentials injected by { @ link RobeAuth } annotation for authentication .
 * @ param id This is the oid of { @ link User }
 * @ param model data of { @ link User }
 * @ return Updates a single { @ link User } matches with the given id . */
@ RobeService ( group = "User" , description = "Updates a single User matches with the given id." ) @ PUT @ UnitOfWork @ Path ( "{id}" ) public User update ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id , @ Valid User model ) { } }

implementation: if ( ! id . equals ( model . getOid ( ) ) ) { throw new WebApplicationException ( Response . status ( 412 ) . build ( ) ) ; } User entity = userDao . findById ( id ) ; if ( entity == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } userDao . detach ( entity ) ; return userDao . update ( model ) ;


signature:
public class UserResource { /** * Updates a single { @ link User } matches with the given id .
 * Status Code :
 * Not Found 404
 * Not Matches 412
 * @ param credentials injected by { @ link RobeAuth } annotation for authentication .
 * @ param id This is the oid of { @ link User }
 * @ param model data of { @ link User }
 * @ return Updates a single { @ link User } matches with the given id . */
@ RobeService ( group = "User" , description = "Updates a single User matches with the given id." ) @ PATCH @ UnitOfWork @ Path ( "{id}" ) public User merge ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id , User model ) { } }

implementation: if ( ! id . equals ( model . getOid ( ) ) ) throw new WebApplicationException ( Response . status ( 412 ) . build ( ) ) ; User dest = userDao . findById ( id ) ; if ( dest == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } Fields . mergeRight ( model , dest ) ; return userDao . update ( dest ) ;


signature:
public class BaseDao { /** * Returns modified list of the entities regarding to the search model .
 * { @ inheritDoc }
 * @ return List of entities . */
public Criteria < T > queryAllStrict ( SearchModel search ) { } }

implementation: Query < T > query = new Query < > ( new TransformerImpl < T > ( this . currentSession ( ) ) ) ; return query . createCriteria ( this . getEntityClass ( ) , search ) ;


signature:
public class BaseDao { /** * Returns modified list of the entities regarding to the search model .
 * { @ inheritDoc }
 * @ return List of entities . */
public Criteria < Map < String , Object > > queryAll ( SearchModel search ) { } }

implementation: Transformer < Map < String , Object > > transformer = new TransformerImpl < > ( this . currentSession ( ) , Criteria . MAP_CLASS ) ; Query < Map < String , Object > > query = new Query < > ( transformer ) ; return query . createCriteria ( this . getEntityClass ( ) , search ) ;


signature:
public class BaseDao { /** * Returns modified list of the entities regarding to the search model .
 * { @ inheritDoc }
 * @ return List of entities . */
public < E > Criteria < E > queryAll ( SearchModel search , Class < E > transformClass ) { } }

implementation: Query < E > query = new Query < > ( new TransformerImpl < > ( this . currentSession ( ) , transformClass ) ) ; return query . createCriteria ( this . getEntityClass ( ) , search ) ;


signature:
public class BaseDao { /** * Returns modified list of the entities regarding to the search model .
 * { @ inheritDoc }
 * @ return List of entities . */
public List < T > findAllStrict ( SearchModel search ) { } }

implementation: Result < T > resultPair = queryAllStrict ( search ) . pairList ( ) ; search . setTotalCount ( resultPair . getTotalCount ( ) ) ; ResponseHeadersUtil . addTotalCount ( search ) ; return resultPair . getList ( ) ;


signature:
public class BaseDao { /** * Returns modified list of the entities regarding to the search model .
 * { @ inheritDoc }
 * @ return List of entities . */
public List < Map < String , Object > > findAll ( SearchModel search ) { } }

implementation: Result < Map < String , Object > > resultPair = queryAll ( search ) . pairList ( ) ; search . setTotalCount ( resultPair . getTotalCount ( ) ) ; ResponseHeadersUtil . addTotalCount ( search ) ; return resultPair . getList ( ) ;


signature:
public class BaseDao { /** * Returns modified list of the entities regarding to the search model .
 * { @ inheritDoc }
 * @ return List of entities . */
public < E > List < E > findAll ( SearchModel search , Class < E > transformClass ) { } }

implementation: Result < E > resultPair = queryAll ( search , transformClass ) . pairList ( ) ; search . setTotalCount ( resultPair . getTotalCount ( ) ) ; ResponseHeadersUtil . addTotalCount ( search ) ; return resultPair . getList ( ) ;


signature:
public class BaseDao { /** * { @ inheritDoc }
 * @ param oid id of the Given Entity
 * @ return returns the result . */
@ SuppressWarnings ( "unchecked" ) public T findById ( Class < ? extends RobeEntity > clazz , Serializable oid ) { } }

implementation: return ( T ) currentSession ( ) . get ( clazz , Preconditions . checkNotNull ( oid ) ) ;


signature:
public class FileAssetServlet { /** * Helps to fix path
 * @ param path to fix
 * @ return */
private String fixPath ( String path ) { } }

implementation: if ( ! path . isEmpty ( ) ) { if ( ! path . endsWith ( "/" ) ) return path + '/' ; else return path ; } else return path ;


signature:
public class MailBundle { /** * Initializes the environment .
 * @ param configuration the configuration object
 * @ param environment the io . robe . admin ' s { @ link io . dropwizard . setup . Environment }
 * @ throws Exception if something goes wrong */
@ Override public void run ( T configuration , Environment environment ) throws Exception { } }

implementation: if ( configuration . getMail ( ) != null && configuration instanceof HasMailConfiguration && configuration instanceof Configuration ) { MailManager . setSender ( new MailSender ( configuration . getMail ( ) ) ) ; } else { LOGGER . warn ( "Bundle included but no configuration (mail) found at yml." ) ; }


signature:
public class TriggerResource { /** * Create a { @ link HTriggerInfo } resource .
 * @ param credentials auto fill by @ { @ link RobeAuth } annotation for authentication .
 * @ param model This is the one model of { @ link HTriggerInfo }
 * @ return create a { @ link HTriggerInfo } resource . */
@ RobeService ( group = "QuartzJob" , description = "Create a HTriggerInfo resource." ) @ POST @ UnitOfWork public HTriggerInfo create ( @ RobeAuth Credentials credentials , @ Valid HTriggerInfo model ) { } }

implementation:
// Save to the DB
HJobInfo job = jobDao . findById ( model . getJobOid ( ) ) ; if ( job == null ) { throw new WebApplicationException ( "Job not found" , Response . Status . NOT_FOUND ) ; } if ( ! job . getProvider ( ) . equals ( HibernateJobInfoProvider . class ) ) { throw new WebApplicationException ( "Trigger is not provided by an editable source." , Response . Status . PRECONDITION_FAILED ) ; } HTriggerInfo record = triggerDao . create ( model ) ; return new TriggerInfoDTO ( record ) ;


signature:
public class TriggerResource { /** * Update a HTriggerInfo resource with the matches given id .
 * Status Code :
 * Not Found 404
 * Not Matches 412
 * @ param credentials auto fill by @ { @ link RobeAuth } annotation for authentication .
 * @ param id This is the oid of { @ link HTriggerInfo }
 * @ param model This is the one model of { @ link HTriggerInfo }
 * @ return Update a { @ link HTriggerInfo } resource with the matches given id . */
@ RobeService ( group = "QuartzJob" , description = "Update a HTriggerInfo resource with the matches given id." ) @ PUT @ UnitOfWork @ Path ( "{id}" ) public HTriggerInfo update ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id , @ Valid HTriggerInfo model ) { } }

implementation: HJobInfo job = jobDao . findById ( model . getJobOid ( ) ) ; if ( job == null ) { throw new WebApplicationException ( "Job not found" , Response . Status . NOT_FOUND ) ; } if ( ! job . getProvider ( ) . equals ( HibernateJobInfoProvider . class ) ) { throw new WebApplicationException ( "Trigger is not provided by an editable source." , Response . Status . PRECONDITION_FAILED ) ; } if ( ! id . equals ( model . getOid ( ) ) ) { throw new WebApplicationException ( "URL trigger id is not same with the payload id" , Response . Status . FORBIDDEN ) ; } HTriggerInfo entity = triggerDao . findById ( id ) ; if ( entity == null ) { throw new WebApplicationException ( "Trigger not found" , Response . Status . NOT_FOUND ) ; } triggerDao . detach ( entity ) ; model = triggerDao . update ( model ) ; return new TriggerInfoDTO ( model ) ;


signature:
public class TriggerResource { /** * Returns all HTriggerInfo as a collection with the matches given job id .
 * @ param credentials auto fill by { @ link RobeAuth } annotation for authentication .
 * @ return all { @ link HTriggerInfo } as a collection */
@ RobeService ( group = "HJobInfo" , description = "Returns all HTriggerInfo as a collection with the matches given job id." ) @ PUT @ Path ( "{id}/resume" ) @ UnitOfWork public boolean resume ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id ) { } }

implementation: HTriggerInfo info = triggerDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobManager . getInstance ( ) . resumeTrigger ( TriggerKey . triggerKey ( info . getName ( ) , info . getGroup ( ) ) ) ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; } return true ;


signature:
public class HqlUtil { /** * Generates Join Query for the given JoinCriteria
 * @ param criteriaJoin
 * @ return */
public static String joinToString ( CriteriaJoin criteriaJoin ) { } }

implementation: StringBuilder builder = new StringBuilder ( "LEFT OUTER JOIN " ) . append ( criteriaJoin . getEntityClass ( ) . getName ( ) ) . append ( " " ) . append ( criteriaJoin . getAlias ( ) ) . append ( " " ) . append ( " ON " ) ; if ( criteriaJoin . getJoinRelations ( ) . size ( ) == 0 ) { throw new RuntimeException ( "Not found any Join Relations in " + criteriaJoin . getAlias ( ) + " Join Criteria ! " ) ; } StringJoiner joiner = new StringJoiner ( " AND " ) ; List < JoinRelation > relationList = criteriaJoin . getJoinRelations ( ) ; for ( JoinRelation joinRelation : relationList ) { StringBuilder relationBuilder = new StringBuilder ( "\n" ) . append ( joinRelation . getRelationCriteria ( ) . getAlias ( ) ) . append ( "." ) . append ( joinRelation . getRelationField ( ) ) . append ( "=" ) . append ( joinRelation . getJoinedCriteria ( ) . getAlias ( ) ) . append ( "." ) . append ( joinRelation . getJoinedField ( ) ) ; joiner . add ( relationBuilder . toString ( ) ) ; } if ( joiner . length ( ) > 0 ) { builder . append ( joiner . toString ( ) ) ; } return builder . toString ( ) ;


signature:
public class TokenBasedAuthResponseFilter { /** * Combines the token and cookie sentence
 * @ param token
 * @ return */
public static String getTokenSentence ( BasicToken token ) throws Exception { } }

implementation:
if ( token == null ) return tokenKey + "=" + cookieSentence ; String sentence = tokenKey + "=" + token . getTokenString ( ) + cookieSentence ; // TODO : Learn how to calculate expire according to the browser time .
// sentence = sentence . replace ( " { expireDate } " , token . getExpirationDate ( ) . toGMTString ( ) ) ;
return sentence ;


signature:
public class TokenBasedAuthResponseFilter { /** * Checks the expiration date of token .
 * Renews and puts at header of response .
 * @ param requestContext
 * @ param responseContext
 * @ return */
@ Override public void filter ( ContainerRequestContext requestContext , ContainerResponseContext responseContext ) throws IOException { } }

implementation: String authToken = extractAuthTokenFromCookieList ( requestContext . getHeaders ( ) . getFirst ( "Cookie" ) ) ; if ( authToken != null && authToken . length ( ) != 0 ) { try { BasicToken token = new BasicToken ( authToken ) ; if ( token . isExpired ( ) ) { LOGGER . debug ( "ExpireDate : " + token . getExpirationDate ( ) . toString ( ) ) ; LOGGER . debug ( "Now: " + DateTime . now ( ) . toDate ( ) . toString ( ) ) ; responseContext . getHeaders ( ) . putSingle ( "Set-Cookie" , getTokenSentence ( null ) ) ; responseContext . setStatusInfo ( Response . Status . UNAUTHORIZED ) ; responseContext . setEntity ( "Token expired. Please login again." ) ; LOGGER . info ( "Token expired. Please login again." ) ; } else { token . setExpiration ( token . getMaxAge ( ) ) ; if ( ! logoutPath . equals ( requestContext . getUriInfo ( ) . getPath ( ) ) ) { String cookie = getTokenSentence ( token ) ; responseContext . getHeaders ( ) . putSingle ( "Set-Cookie" , cookie ) ; } } } catch ( Exception e ) { LOGGER . error ( "Token re-creation failed" , e . getMessage ( ) ) ; responseContext . setStatusInfo ( Response . Status . UNAUTHORIZED ) ; } }


signature:
public class TokenBasedAuthResponseFilter { /** * Extracts the accesstoken from cookies
 * @ param cookieList
 * @ return */
private String extractAuthTokenFromCookieList ( String cookieList ) { } }

implementation: if ( cookieList == null || cookieList . length ( ) == 0 ) { return null ; } String [ ] cookies = cookieList . split ( ";" ) ; for ( String cookie : cookies ) { if ( cookie . trim ( ) . startsWith ( tokenKey ) ) { return cookie . trim ( ) . substring ( tokenKey . length ( ) + 1 ) ; } } return null ;


signature:
public class JerseyUtil { /** * Registers any Guice - bound providers or root resources . */
public static void registerGuiceBound ( Injector injector , final JerseyEnvironment environment ) { } }

implementation:
while ( injector != null ) { for ( Key < ? > key : injector . getBindings ( ) . keySet ( ) ) { Type type = key . getTypeLiteral ( ) . getType ( ) ; if ( type instanceof Class ) { Class < ? > c = ( Class ) type ; if ( isProviderClass ( c ) ) { logger . info ( "Registering {} as a provider class" , c . getName ( ) ) ; environment . register ( c ) ; } else if ( isRootResourceClass ( c ) ) { // Jersey rejects resources that it doesn ' t think are acceptable
// Including abstract classes and interfaces , even if there is a valid Guice binding .
if ( Resource . isAcceptable ( c ) ) { logger . info ( "Registering {} as a root resource class" , c . getName ( ) ) ; environment . register ( c ) ; } else { logger . warn ( "Class {} was not registered as a resource. Bind a concrete implementation instead." , c . getName ( ) ) ; } } } } injector = injector . getParent ( ) ; }


signature:
public class AuthResource { /** * check username and password for authentication
 * Status Code :
 * UNAUTHORIZED no have authentication .
 * INTERNAL _ SERVER _ ERROR Blocked .
 * @ param request HttpServletRequest
 * @ param credentials username and password ( SHA256)
 * @ return { @ link Response }
 * @ throws Exception for createToken */
@ POST @ UnitOfWork ( flushMode = FlushMode . ALWAYS ) @ Path ( "login" ) @ Timed public Response login ( @ Context HttpServletRequest request , Map < String , String > credentials ) throws Exception { } }

implementation: Optional < User > user = userDao . findByUsername ( credentials . get ( "username" ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . UNAUTHORIZED ) ; } else if ( user . get ( ) . getPassword ( ) . equals ( credentials . get ( "password" ) ) ) { if ( ! user . get ( ) . isActive ( ) ) return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( "User blocked." ) . build ( ) ; Map < String , String > attributes = new HashMap < > ( ) ; attributes . put ( "userAgent" , request . getHeader ( "User-Agent" ) ) ; attributes . put ( "remoteAddr" , request . getRemoteAddr ( ) ) ; BasicToken token = new BasicToken ( user . get ( ) . getUserId ( ) , user . get ( ) . getEmail ( ) , DateTime . now ( ) , attributes ) ; token . setExpiration ( token . getMaxAge ( ) ) ; credentials . remove ( "password" ) ; credentials . put ( "domain" , TokenBasedAuthResponseFilter . getTokenSentence ( null ) ) ; user . get ( ) . setLastLoginTime ( DateTime . now ( ) . toDate ( ) ) ; user . get ( ) . setFailCount ( 0 ) ; logAction ( new ActionLog ( "LOGIN" , null , user . get ( ) . toString ( ) , true , request . getRemoteAddr ( ) ) ) ; return Response . ok ( ) . header ( "Set-Cookie" , TokenBasedAuthResponseFilter . getTokenSentence ( token ) ) . entity ( credentials ) . build ( ) ; } else { if ( ! user . get ( ) . isActive ( ) ) { logAction ( new ActionLog ( "LOGIN" , "Blocked" , user . get ( ) . toString ( ) , false , request . getRemoteAddr ( ) ) ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( "User blocked." ) . build ( ) ; } int failCount = user . get ( ) . getFailCount ( ) + 1 ; user . get ( ) . setFailCount ( failCount ) ; boolean block = failCount >= Integer . valueOf ( ( String ) SystemParameterCache . get ( "USER_BLOCK_FAIL_LIMIT" , "3" ) ) ; if ( block ) user . get ( ) . setActive ( false ) ; userDao . update ( user . get ( ) ) ; logAction ( new ActionLog ( "LOGIN" , "Wrong Password" , user . get ( ) . toString ( ) , false , request . getRemoteAddr ( ) ) ) ; return Response . status ( Response . Status . UNAUTHORIZED ) . build ( ) ; }


signature:
public class AuthResource { /** * Log out
 * @ param credentials injected by { @ link RobeAuth } annotation for authentication .
 * @ return { @ link User } when logout
 * @ throws Exception for clear permission cache */
@ POST @ UnitOfWork @ Path ( "logout" ) @ Timed public Response logout ( @ RobeAuth Credentials credentials , @ Context HttpServletRequest request ) throws Exception { } }

implementation: Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . UNAUTHORIZED ) ; } else { BasicToken . clearPermissionCache ( credentials . getUsername ( ) ) ; user . get ( ) . setLastLogoutTime ( DateTime . now ( ) . toDate ( ) ) ; logAction ( new ActionLog ( "LOGOUT" , null , user . get ( ) . toString ( ) , true , request . getRemoteAddr ( ) ) ) ; return Response . ok ( ) . header ( "Set-Cookie" , TokenBasedAuthResponseFilter . getTokenSentence ( null ) ) . build ( ) ; }


signature:
public class AuthResource { /** * User Information Returns
 * Status Code :
 * UNAUTHORIZED no have authentication .
 * @ param credentials injected by { @ link RobeAuth } annotation for authentication .
 * @ return { @ link User }
 * @ throws Exception for not found user */
@ Path ( "profile" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public User getProfile ( @ RobeAuth Credentials credentials ) { } }

implementation: Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . UNAUTHORIZED ) ; } else return user . get ( ) ;


signature:
public class AuthResource { /** * User Change Password
 * Status Code :
 * NOT _ FOUND not found user .
 * PRECONDITION _ FAILED change passsword error .
 * @ param request HttpServletRequest
 * @ param passwords password ( SHA256 ) , newpassword ( SHA256 ) and newpasswordrpt ( SHA256)
 * @ param credentials injected by { @ link RobeAuth } annotation for authentication .
 * @ return { @ link Response }
 * @ throws Exception for not found user */
@ POST @ UnitOfWork @ Path ( "password" ) @ Timed public Response changePassword ( @ Context HttpServletRequest request , @ RobeAuth Credentials credentials , Map < String , String > passwords ) { } }

implementation: Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . NOT_FOUND ) ; } else if ( user . get ( ) . getPassword ( ) . equals ( passwords . get ( "password" ) ) ) { if ( passwords . get ( "newPassword" ) . equals ( passwords . get ( "newPasswordRepeat" ) ) ) { user . get ( ) . setPassword ( passwords . get ( "newPassword" ) ) ; return Response . status ( Response . Status . OK ) . entity ( "Your password has been updated" ) . build ( ) ; } else { return Response . status ( Response . Status . PRECONDITION_FAILED ) . entity ( "Your new password does not match." ) . build ( ) ; } } else { return Response . status ( Response . Status . PRECONDITION_FAILED ) . entity ( "Your password is incorrect." ) . build ( ) ; }


signature:
public class TokenAuthenticator { /** * Creates { @ link Optional } { @ link io . robe . auth . Credentials } instance from provided tokenString
 * @ param tokenString tokenString to decode .
 * @ return Optional instance of a { @ link io . robe . auth . Credentials } which created from tokenString
 * @ throws AuthenticationException */
@ Override public Optional < BasicToken > authenticate ( String tokenString ) throws AuthenticationException { } }

implementation:
tokenString = tokenString . replaceAll ( "\"" , "" ) ; LOGGER . debug ( "Authenticating from database:  " + tokenString ) ; try { // Decode tokenString and get user
BasicToken token = new BasicToken ( tokenString ) ; Optional < UserEntry > user = ( Optional < UserEntry > ) userStore . findByUsername ( token . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { LOGGER . warn ( "User is not available: " + tokenString ) ; return Optional . empty ( ) ; } // If user exists and active than check Service Permissions for authorization controls
if ( user . get ( ) . isActive ( ) ) { if ( token . getPermissions ( ) == null ) { LOGGER . debug ( "Loading Permissions from DB: " + tokenString ) ; Set < String > permissions = new HashSet < String > ( ) ; Set < PermissionEntry > rolePermissions = new HashSet < PermissionEntry > ( ) ; // If user role is a group than add sub role permissions to group
Optional < RoleEntry > role = ( Optional < RoleEntry > ) roleStore . findByRoleId ( user . get ( ) . getRoleId ( ) ) ; getAllRolePermissions ( role . get ( ) , rolePermissions ) ; for ( PermissionEntry permission : rolePermissions ) { if ( permission . getType ( ) . equals ( PermissionEntry . Type . SERVICE ) ) { Optional < ? extends ServiceEntry > service = serviceStore . findByCode ( permission . getRestrictedItemId ( ) ) ; if ( service . isPresent ( ) ) { permissions . add ( service . get ( ) . getPath ( ) + ":" + service . get ( ) . getMethod ( ) ) ; } } } // Create credentials with user info and permission list
token . setPermissions ( Collections . unmodifiableSet ( permissions ) ) ; } else { LOGGER . debug ( "Loading Permissions from Cache: " + tokenString ) ; } return Optional . ofNullable ( token ) ; } } catch ( Exception e ) { LOGGER . error ( tokenString , e ) ; } return Optional . empty ( ) ;


signature:
public class TokenAuthenticator { /** * Fill permission list with role and sub - role permissions recursively .
 * @ param parent Role to traverse .
 * @ param rolePermissions list of all permissions of the given role . */
private void getAllRolePermissions ( RoleEntry parent , Set < PermissionEntry > rolePermissions ) { } }

implementation: rolePermissions . addAll ( permissionStore . findByRoleId ( parent . getId ( ) ) ) ; Set < RoleGroupEntry > roleGroupEntries = ( Set < RoleGroupEntry > ) roleGroupStore . findByGroupId ( parent . getId ( ) ) ; for ( RoleGroupEntry entry : roleGroupEntries ) { Optional < RoleEntry > role = ( Optional < RoleEntry > ) roleStore . findByRoleId ( entry . getRoleId ( ) ) ; getAllRolePermissions ( role . get ( ) , rolePermissions ) ; }


signature:
public class JobResource { /** * Return all HJobInfo as a collection
 * @ param credentials auto fill by { @ link RobeAuth } annotation for authentication .
 * @ return all { @ link HJobInfo } as a collection */
@ RobeService ( group = "HJobInfo" , description = "Returns all HJobInfo as a collection." ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public Collection < JobInfoDTO > getAll ( @ RobeAuth Credentials credentials , @ SearchParam SearchModel search ) { } }

implementation: List < JobInfoDTO > dtoList = new LinkedList < > ( ) ; for ( HJobInfo info : jobDao . findAllStrict ( search ) ) { JobInfoDTO dto = new JobInfoDTO ( info ) ; try { if ( ! JobManager . getInstance ( ) . isScheduledJob ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . UNSCHEDULED ) ; } else { if ( JobManager . getInstance ( ) . isPausedJob ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . PAUSED ) ; } else { dto . setStatus ( JobInfoDTO . Status . ACTIVE ) ; } } } catch ( SchedulerException e ) { e . printStackTrace ( ) ; } dtoList . add ( dto ) ; } return dtoList ;


signature:
public class JobResource { /** * Return a HJobInfo resource with the matches given id .
 * Status Code :
 * Not Found 404
 * @ param credentials auto fill by @ { @ link RobeAuth } annotation for authentication .
 * @ param id This is the oid of { @ link HJobInfo }
 * @ return a { @ link HJobInfo } resource with the matches given id . */
@ RobeService ( group = "HJobInfo" , description = "Returns a HJobInfo resource with the matches given id." ) @ Path ( "{id}" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public HJobInfo get ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id ) { } }

implementation: HJobInfo entity = jobDao . findById ( id ) ; if ( entity == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } return entity ;


signature:
public class JobResource { /** * Returns all HTriggerInfo as a collection with the matches given job id .
 * @ param credentials auto fill by { @ link RobeAuth } annotation for authentication .
 * @ return all { @ link HTriggerInfo } as a collection */
@ RobeService ( group = "HJobInfo" , description = "Returns all HTriggerInfo as a collection with the matches given job id." ) @ GET @ Path ( "{id}/triggers" ) @ UnitOfWork public List < TriggerInfoDTO > getJobTriggers ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id ) { } }

implementation: List < TriggerInfoDTO > dtos = new LinkedList < > ( ) ; for ( HTriggerInfo info : triggerDao . findByJobOid ( id ) ) { TriggerInfoDTO dto = new TriggerInfoDTO ( info ) ; try { if ( ! JobManager . getInstance ( ) . isScheduledTrigger ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . UNSCHEDULED ) ; } else { if ( JobManager . getInstance ( ) . isPausedTrigger ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . PAUSED ) ; } else { dto . setStatus ( JobInfoDTO . Status . ACTIVE ) ; } } } catch ( SchedulerException e ) { e . printStackTrace ( ) ; } dtos . add ( dto ) ; } return dtos ;


signature:
public class JobResource { /** * Returns all HTriggerInfo as a collection with the matches given job id .
 * @ param credentials auto fill by { @ link RobeAuth } annotation for authentication .
 * @ return all { @ link HTriggerInfo } as a collection */
@ RobeService ( group = "HJobInfo" , description = "Returns all HTriggerInfo as a collection with the matches given job id." ) @ PUT @ Path ( "{id}/schedule" ) @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public boolean schedule ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id ) { } }

implementation: HJobInfo info = jobDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobInfo dto = new HibernateJobInfoProvider ( ) . getJob ( info . getJobClass ( ) ) ; JobDetail detail = HibernateJobInfoProvider . convert2JobDetail ( dto ) ; Set < Trigger > triggers = new HashSet < > ( dto . getTriggers ( ) . size ( ) ) ; for ( TriggerInfo triggerInfo : dto . getTriggers ( ) ) { if ( triggerInfo . getType ( ) . equals ( TriggerInfo . Type . CRON ) || triggerInfo . getType ( ) . equals ( TriggerInfo . Type . SIMPLE ) ) { triggers . add ( HibernateJobInfoProvider . convert2Trigger ( triggerInfo , dto ) ) ; } } JobManager . getInstance ( ) . scheduleJob ( detail , triggers , false ) ; return true ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; }


signature:
public class JobResource { /** * Returns all HTriggerInfo as a collection with the matches given job id .
 * @ param credentials auto fill by { @ link RobeAuth } annotation for authentication .
 * @ return all { @ link HTriggerInfo } as a collection */
@ RobeService ( group = "HJobInfo" , description = "Returns all HTriggerInfo as a collection with the matches given job id." ) @ PUT @ Path ( "{id}/pause" ) @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public boolean pause ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id ) { } }

implementation: HJobInfo info = jobDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobManager . getInstance ( ) . pauseJob ( info . getName ( ) , info . getGroup ( ) ) ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; } return true ;


signature:
public class JobResource { /** * Returns all HTriggerInfo as a collection with the matches given job id .
 * @ param credentials auto fill by { @ link RobeAuth } annotation for authentication .
 * @ return all { @ link HTriggerInfo } as a collection */
@ RobeService ( group = "HJobInfo" , description = "Returns all HTriggerInfo as a collection with the matches given job id." ) @ PUT @ Path ( "{id}/resume" ) @ UnitOfWork public boolean resume ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id ) { } }

implementation: HJobInfo info = jobDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobManager . getInstance ( ) . resumeJob ( info . getName ( ) , info . getGroup ( ) ) ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; } return true ;