signature:
public class WrapperServlet { /** * Executes the desired method call with a new instance of the { @ link ResourceServlet } implementation .
 * Transaction management is done here .
 * @ param call
 * @ param uow
 * @ param req
 * @ param resp */
private final void dispatch ( Method call , UnitOfWork uow , HttpServletRequest req , HttpServletResponse resp ) { } }

implementation: if ( uow == null ) { try { ResourceServlet servlet = GuiceBundle . getInjector ( ) . getInstance ( servletClass ) ; call . invoke ( servlet , req , resp ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else { SessionFactory sessionFactory = GuiceBundle . getInjector ( ) . getInstance ( SessionFactory . class ) ; Session session = sessionFactory . openSession ( ) ; try { configureSession ( session , uow ) ; ManagedSessionContext . bind ( session ) ; beginTransaction ( session , uow ) ; try { ResourceServlet servlet = ( singleton == null ) ? singleton : GuiceBundle . getInjector ( ) . getInstance ( servletClass ) ; call . invoke ( servlet , req , resp ) ; commitTransaction ( session , uow ) ; } catch ( Exception e ) { rollbackTransaction ( session , uow ) ; throw new RuntimeException ( e ) ; } } finally { session . close ( ) ; ManagedSessionContext . unbind ( sessionFactory ) ; } }


signature:
public class ProjectionList { /** * Adds a projection to this list of projections after wrapping it with an alias
 * @ param projection The projection to add
 * @ param alias The alias to apply to the projection
 * @ return { @ code this } , for method chaining
 * @ see org . hibernate . criterion . Projections # alias */
public ProjectionList add ( Projection projection , String alias ) { } }

implementation: return add ( Projections . alias ( projection , alias ) ) ;


signature:
public class MenuResource { /** * get menu for logged user
 * @ param credentials injected by { @ link RobeAuth } annotation for authentication .
 * @ return user { @ link MenuItem } as collection */
@ RobeService ( group = "Menu" , description = "Get menu for logged user" ) @ Path ( "user" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) @ CacheControl ( noCache = true ) public List < MenuItem > getUserHierarchicalMenu ( @ RobeAuth Credentials credentials ) { } }

implementation: Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; Set < Permission > permissions = new HashSet < Permission > ( ) ; Role parent = roleDao . findById ( user . get ( ) . getRoleOid ( ) ) ; getAllRolePermissions ( parent , permissions ) ; Set < String > menuOids = new HashSet < String > ( ) ; List < MenuItem > items = convertMenuToMenuItem ( menuDao . findHierarchicalMenu ( ) ) ; items = readMenuHierarchical ( items ) ; for ( Permission permission : permissions ) { if ( permission . getType ( ) . equals ( Permission . Type . MENU ) ) { menuOids . add ( permission . getRestrictedItemOid ( ) ) ; } } List < MenuItem > permittedItems = new LinkedList < MenuItem > ( ) ; createMenuWithPermissions ( menuOids , items , permittedItems ) ; return permittedItems ;


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

implementation: return menuDao . create ( model ) ;


signature:
public class JobInfoProvider { /** * Creates an identical JobDetail instance from the given parameters .
 * @ param info job annotation
 * @ return */
public static JobDetail convert2JobDetail ( JobInfo info ) { } }

implementation: JobKey jobKey = JobKey . jobKey ( info . getName ( ) ) ; JobDetail jobDetail = newJob ( info . getJobClass ( ) ) . withIdentity ( jobKey ) . build ( ) ; return jobDetail ;


signature:
public class JobInfoProvider { /** * Creates an identical Trigger instance from the given annotation .
 * @ param trig
 * @ return */
public static Trigger convert2Trigger ( TriggerInfo trig , JobInfo job ) { } }

implementation: TriggerBuilder < Trigger > builder = newTrigger ( ) ; builder . withIdentity ( trig . getName ( ) , trig . getGroup ( ) ) ; builder . forJob ( job . getName ( ) , job . getGroup ( ) ) ; switch ( trig . getType ( ) ) { case CRON : setStartEndTime ( trig , builder ) ; if ( ! trig . getCron ( ) . isEmpty ( ) ) builder . withSchedule ( CronScheduleBuilder . cronSchedule ( trig . getCron ( ) ) ) ; break ; case SIMPLE : setStartEndTime ( trig , builder ) ; setCountIntervalValues ( trig , builder ) ; break ; } return builder . build ( ) ;


signature:
public class JobInfoProvider { /** * Helps to set count and intervals
 * @ param dto
 * @ param builder */
private static void setCountIntervalValues ( TriggerInfo dto , TriggerBuilder < org . quartz . Trigger > builder ) { } }

implementation: SimpleScheduleBuilder builderSc = SimpleScheduleBuilder . simpleSchedule ( ) ; if ( dto . getRepeatCount ( ) != 0 ) builderSc . withRepeatCount ( dto . getRepeatCount ( ) ) ; if ( dto . getRepeatInterval ( ) > 0 ) builderSc . withIntervalInMilliseconds ( dto . getRepeatInterval ( ) ) ; builder . withSchedule ( builderSc ) ;


signature:
public class JobInfoProvider { /** * Helps to set start and end times
 * @ param dto
 * @ param builder */
private static void setStartEndTime ( TriggerInfo dto , TriggerBuilder < org . quartz . Trigger > builder ) { } }

implementation: if ( dto . getStartTime ( ) > - 1 ) builder . startAt ( new Date ( dto . getStartTime ( ) ) ) ; else builder . startNow ( ) ; if ( dto . getEndTime ( ) > - 1 ) builder . endAt ( new Date ( dto . getEndTime ( ) ) ) ;


signature:
public class MailManager { /** * Takes the mail item into the queue and manages the mail sender thread .
 * If thread is alive it will send the mail at the end of current thread queue .
 * Else a new thread will be created and started .
 * @ param item MailItem to send .
 * @ return true if item added to the queue successfully . */
public static boolean sendMail ( MailItem item ) { } }

implementation:
LOGGER . debug ( "Mail : " + item . toString ( ) ) ; boolean result = queue . add ( item ) ; LOGGER . info ( "Adding mail to queue. Queue size: " + queue . size ( ) ) ; // If thread is alive leave the job to it
// Else create new thread and start .
if ( ! consumerThread . isAlive ( ) ) { consumerThread = new Thread ( consumer ) ; consumerThread . start ( ) ; } return result ;


signature:
public class BufferedStreamingOutput { /** * Called to write the message body .
 * @ param output the OutputStream to write to .
 * @ throws java . io . IOException if an IO error is encountered
 * @ throws javax . ws . rs . WebApplicationException if a specific
 * HTTP error response needs to be produced . Only effective if thrown prior
 * to any bytes being written to output . */
@ Override public void write ( OutputStream output ) throws IOException , WebApplicationException { } }

implementation:
// Write until available bytes are less than buffer .
while ( bufferedInputStream . available ( ) > buffer . length ) { bufferedInputStream . read ( buffer ) ; output . write ( buffer ) ; } // Write one more time to finish and exit .
buffer = new byte [ bufferedInputStream . available ( ) ] ; bufferedInputStream . read ( buffer ) ; output . write ( buffer ) ; bufferedInputStream . close ( ) ;


signature:
public class QuartzBundle { /** * Initializes the environment . Forwards the configuration to Quartz .
 * Collect { @ link JobInfoProvider } classes
 * Initializes scheduler
 * Collects all subtypes of { @ link org . quartz . Job } annotated with { @ link RobeJob } including { @ link @ RobeTrigger } ' s
 * * Collects additional triggers from providers
 * * Registers them all for future control .
 * @ param configuration the configuration object
 * @ param environment the service ' s { @ link io . dropwizard . setup . Environment }
 * @ throws Exception if something goes wrong */
@ Override public void run ( T configuration , Environment environment ) { } }

implementation: QuartzConfiguration qConf = configuration . getQuartz ( ) ; try { initializeScheduler ( qConf . getProperties ( ) ) ; collectAndScheduleJobs ( qConf . getScanPackages ( ) ) ; environment . lifecycle ( ) . manage ( new ManagedQuartz ( getOnStartJobs ( ) , getOnStopJobs ( ) ) ) ; } catch ( SchedulerException e ) { LOGGER . error ( "SchedulerException:" , e ) ; }


signature:
public class QuartzBundle { /** * Initialize scheduler and start JobManager
 * @ param properties
 * @ throws SchedulerException */
private void initializeScheduler ( Properties properties ) throws SchedulerException { } }

implementation: SchedulerFactory factory = new StdSchedulerFactory ( properties ) ; Scheduler scheduler = factory . getScheduler ( ) ; scheduler . start ( ) ; JobManager . initialize ( scheduler ) ;


signature:
public class Converter { /** * Returns an ordered list of the fields which belongs to the given class .
 * @ param clazz class to get types .
 * @ return ordered list of fields . */
protected final Collection < FieldEntry > getFields ( Class clazz ) { } }

implementation: LinkedList < FieldEntry > fieldList = getAllFields ( clazz ) ; Collections . sort ( fieldList , new Comparator < FieldEntry > ( ) { public int compare ( FieldEntry o1 , FieldEntry o2 ) { return o1 . compareTo ( o2 ) ; } } ) ; return fieldList ;


signature:
public class Converter { /** * Returns a map of the fields which belongs to the given class with field name as key .
 * @ param clazz class to get types .
 * @ return ordered list of fields . */
protected final Map < String , Field > getFieldMap ( Class clazz ) { } }

implementation: Map < String , Field > fieldList = new HashMap < String , Field > ( ) ; for ( FieldEntry entry : getAllFields ( clazz ) ) { Field field = entry . getValue ( ) ; fieldList . put ( field . getName ( ) , field ) ; } return fieldList ;


signature:
public class RobeApplication { /** * Adds
 * Hibernate bundle for PROVIDER connection
 * Asset bundle for io . robe . admin screens and
 * Class scanners for
 * < ul >
 * < li > Entities < / li >
 * < li > HealthChecks < / li >
 * < li > Providers < / li >
 * < li > InjectableProviders < / li >
 * < li > Resources < / li >
 * < li > Tasks < / li >
 * < li > Managed objects < / li >
 * < / ul >
 * @ param bootstrap */
@ Override public void initialize ( Bootstrap < T > bootstrap ) { } }

implementation: T config = loadConfiguration ( bootstrap ) ; RobeHibernateBundle < T > hibernateBundle = RobeHibernateBundle . createInstance ( config . getHibernate ( ) . getScanPackages ( ) , config . getHibernate ( ) . getEntities ( ) ) ; List < Module > modules = new LinkedList < > ( ) ; modules . add ( new HibernateModule ( hibernateBundle ) ) ; bootstrap . addBundle ( new GuiceBundle < T > ( modules , bootstrap . getApplication ( ) . getConfigurationClass ( ) ) ) ; bootstrap . addBundle ( hibernateBundle ) ; bootstrap . addBundle ( new TokenAuthBundle < T > ( ) ) ; bootstrap . addCommand ( new InitializeCommand ( this , hibernateBundle ) ) ; bootstrap . addBundle ( new QuartzBundle < T > ( ) ) ; bootstrap . addBundle ( new MailBundle < T > ( ) ) ; bootstrap . addBundle ( new AdvancedAssetBundle < T > ( ) ) ;


signature:
public class RobeApplication { /** * { @ inheritDoc }
 * In addition adds exception mapper .
 * @ param configuration
 * @ param environment
 * @ throws Exception */
@ UnitOfWork @ Override public void run ( T configuration , Environment environment ) throws Exception { } }

implementation: TokenFactory . authenticator = new TokenAuthenticator ( GuiceBundle . getInjector ( ) . getInstance ( UserDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( ServiceDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( RoleDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( PermissionDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( RoleGroupDao . class ) ) ; TokenFactory . tokenKey = configuration . getAuth ( ) . getTokenKey ( ) ; environment . jersey ( ) . register ( RobeExceptionMapper . class ) ; environment . jersey ( ) . register ( new ExceptionMapperBinder ( true ) ) ; environment . jersey ( ) . register ( new SearchFactoryProvider . Binder ( ) ) ; environment . jersey ( ) . register ( MultiPartFeature . class ) ; if ( configuration . getRecaptcha ( ) != null ) { new ReCaptchaValidation ( configuration . getRecaptcha ( ) ) ; } JobPersister jobPersister = new JobPersister ( QuartzBundle . JOBS ) ;


signature:
public class RoleResource { /** * Returns all services and menus collection with the matches given Role id .
 * @ param credentials Injected by { @ link RobeAuth } annotation for authentication .
 * @ param id This is Role oid
 * @ return JSONObject ( MENU and SERVICE ) */
@ RobeService ( group = "Permission" , description = "Returns all services and menus collection with the matches given Role id." ) @ GET @ Path ( "{id}/permissions" ) @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public Map < String , Object > getRolePermissions ( @ RobeAuth Credentials credentials , @ PathParam ( "id" ) String id ) { } }

implementation: List < Permission > permissions = new ArrayList < > ( ) ; List < Service > services = new ArrayList < > ( ) ; List < Menu > menus = new ArrayList < > ( ) ; Role role = roleDao . findById ( id ) ; getAllRolePermissions ( role , permissions ) ; for ( Permission permission : permissions ) { if ( permission . getType ( ) . equals ( PermissionEntry . Type . SERVICE ) ) { Service service = serviceDao . findById ( permission . getRestrictedItemOid ( ) ) ; if ( service != null ) { if ( services . indexOf ( service ) == - 1 ) { services . add ( service ) ; } } } else if ( permission . getType ( ) . equals ( PermissionEntry . Type . MENU ) ) { Menu menu = menuDao . findById ( permission . getRestrictedItemOid ( ) ) ; if ( menu != null ) { if ( menus . indexOf ( menu ) == - 1 ) { menus . add ( menu ) ; } } } } Map < String , Object > response = new HashMap < > ( ) ; response . put ( "menu" , menus ) ; response . put ( "service" , services ) ; return response ;


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

implementation: return roleDao . create ( model ) ;


signature:
public class ServiceResource { /** * Create { @ link Service ) resource and matches with the given id .
 * @ param credentials Injected by { @ link RobeAuth } annotation for authentication .
 * @ param model This is the one model of { @ link Service }
 * @ return Create { @ link Service ) resource and return given Service path link at header Location = example / { id ] . */
@ RobeService ( group = "Service" , description = "Create Service resource and return given Service path link at header Location=example/{id]." ) @ POST @ UnitOfWork public Service create ( @ RobeAuth Credentials credentials , @ Valid Service model ) { } }

implementation: return serviceDao . create ( model ) ;


signature:
public class ServiceResource { /** * refreshing service with description
 * TODO exception handler
 * @ param credentials Injected by { @ link RobeAuth } annotation for authentication .
 * @ return Response . OK */
@ Path ( "refresh" ) @ GET @ UnitOfWork public Response refreshServices ( @ RobeAuth Credentials credentials ) { } }

implementation: GuiceConfiguration configuration = GuiceBundle . getConfiguration ( ) ; Reflections reflections = new Reflections ( configuration . getScanPackages ( ) , this . getClass ( ) . getClassLoader ( ) ) ; Set < Class < ? > > services = reflections . getTypesAnnotatedWith ( Path . class ) ; int count = 0 ; for ( Class service : services ) { String parentPath = "/" + ( ( Path ) service . getAnnotation ( Path . class ) ) . value ( ) ; for ( Method method : service . getMethods ( ) ) { String httpMethod = ifServiceGetHttpMethod ( method ) ; if ( httpMethod == null ) { continue ; } String path = parentPath ; path = extractPath ( method , path ) ; io . robe . admin . hibernate . entity . Service entity = serviceDao . findByPathAndMethod ( path , ServiceEntry . Method . valueOf ( httpMethod ) ) ; RobeService robeService = ( RobeService ) method . getAnnotation ( RobeService . class ) ; if ( entity != null ) { if ( robeService != null ) { entity . setDescription ( robeService . description ( ) ) ; entity . setGroup ( robeService . group ( ) ) ; serviceDao . update ( entity ) ; } continue ; } entity = new io . robe . admin . hibernate . entity . Service ( ) ; entity . setPath ( path ) ; entity . setMethod ( io . robe . admin . hibernate . entity . Service . Method . valueOf ( httpMethod ) ) ; if ( robeService != null ) { entity . setDescription ( robeService . description ( ) ) ; entity . setGroup ( robeService . group ( ) ) ; } else { entity . setGroup ( "UNGROUPED" ) ; entity . setDescription ( "" ) ; } entity . setDescription ( entity . getDescription ( ) + " (" + entity . getMethod ( ) + " " + entity . getPath ( ) + ")" ) ; serviceDao . create ( entity ) ; count ++ ; } } return Response . ok ( count ) . build ( ) ;


signature:
public class RobeExceptionMapper { /** * Parses or wraps the exception and transforms it to a human readable json loaded response .
 * @ param e Exception to transform
 * @ return error response */
@ Override public Response toResponse ( Exception e ) { } }

implementation: String id = System . nanoTime ( ) + "" ; LOGGER . error ( id , e ) ; if ( e instanceof RobeRuntimeException ) { return ( ( RobeRuntimeException ) e ) . getResponse ( id ) ; } else if ( e instanceof ConstraintViolationException ) { ConstraintViolationException exception = ( ConstraintViolationException ) e ; RobeMessage [ ] errors = new RobeMessage [ exception . getConstraintViolations ( ) . size ( ) ] ; int i = 0 ; for ( ConstraintViolation error : exception . getConstraintViolations ( ) ) { errors [ i ++ ] = new RobeMessage . Builder ( ) . message ( error . getMessage ( ) ) . status ( 422 ) . id ( id ) . build ( ) ; } return Response . status ( 422 ) . entity ( errors ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } else if ( e instanceof WebApplicationException ) { WebApplicationException we = ( WebApplicationException ) e ; RobeMessage error = new RobeMessage . Builder ( ) . id ( id ) . message ( we . getMessage ( ) ) . status ( we . getResponse ( ) . getStatus ( ) ) . build ( ) ; return Response . fromResponse ( we . getResponse ( ) ) . entity ( error ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } else { if ( e . getClass ( ) . getName ( ) . equals ( "org.hibernate.exception.ConstraintViolationException" ) ) { if ( e . getCause ( ) != null && e . getCause ( ) . getMessage ( ) != null ) { RobeMessage error = new RobeMessage . Builder ( ) . message ( e . getCause ( ) . getMessage ( ) . split ( "for" ) [ 0 ] ) . status ( Response . Status . CONFLICT . getStatusCode ( ) ) . id ( id ) . build ( ) ; return Response . status ( Response . Status . CONFLICT ) . entity ( error ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } } RobeMessage error = new RobeMessage . Builder ( ) . message ( e . getMessage ( ) ) . id ( id ) . build ( ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( error ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; }


signature:
public class BasicToken { /** * Configure method for Token generation configurations and encryptor configure
 * @ param configuration confiuration for auth bundle */
public static void configure ( TokenBasedAuthConfiguration configuration ) { } }

implementation:
encryptor . setPoolSize ( configuration . getPoolSize ( ) ) ; // This would be a good value for a 4 - core system
if ( configuration . getServerPassword ( ) . equals ( "auto" ) ) { encryptor . setPassword ( UUID . randomUUID ( ) . toString ( ) ) ; } else { encryptor . setPassword ( configuration . getServerPassword ( ) ) ; } encryptor . setAlgorithm ( configuration . getAlgorithm ( ) ) ; encryptor . initialize ( ) ; BasicToken . defaultMaxAge = configuration . getMaxage ( ) ; // Create cache for permissions .
cache = CacheBuilder . newBuilder ( ) . expireAfterAccess ( defaultMaxAge , TimeUnit . SECONDS ) . expireAfterWrite ( defaultMaxAge , TimeUnit . SECONDS ) . build ( ) ;


signature:
public class BasicToken { /** * Generates attribute has with ' userAgent ' , ' remoteAddr ' keys .
 * Combines them and hashes with SHA256 and sets the variable .
 * @ param attributes */
private void generateAttributesHash ( Map < String , String > attributes ) { } }

implementation:
StringBuilder attr = new StringBuilder ( ) ; attr . append ( attributes . get ( "userAgent" ) ) ; // attr . append ( attributes . get ( " remoteAddr " ) ) ; TODO : add remote ip address after you find how to get remote IP from HttpContext
attributesHash = Hashing . sha256 ( ) . hashString ( attr . toString ( ) , StandardCharsets . UTF_8 ) . toString ( ) ; resetTokenString ( ) ;


signature:
public class BasicToken { /** * Generates a tokenString with a new expiration date and assigns it .
 * @ return new tokenString
 * @ throws Exception */
private String generateTokenString ( ) throws Exception { } }

implementation:
// Renew age
// Stringify token data
StringBuilder dataString = new StringBuilder ( ) ; dataString . append ( getUserId ( ) ) . append ( SEPARATOR ) . append ( getUsername ( ) ) . append ( SEPARATOR ) . append ( getExpirationDate ( ) . getTime ( ) ) . append ( SEPARATOR ) . append ( attributesHash ) ; // Encrypt token data string
String newTokenString = encryptor . encrypt ( dataString . toString ( ) ) ; newTokenString = BaseEncoding . base16 ( ) . encode ( newTokenString . getBytes ( ) ) ; tokenString = newTokenString ; return newTokenString ;


signature:
public class MailSender { /** * Sends a mail with the given item .
 * @ param item MailItem to be send . */
public void sendMessage ( MailItem item ) throws MessagingException { } }

implementation:
checkNotNull ( item . getReceivers ( ) ) ; checkNotNull ( item . getReceivers ( ) . get ( 0 ) ) ; checkNotNull ( item . getTitle ( ) ) ; checkNotNull ( item . getBody ( ) ) ; // If sender is empty send with the account sender .
Message msg = new MimeMessage ( session ) ; if ( item . getSender ( ) == null || item . getSender ( ) . length ( ) == 0 ) { item . setSender ( configuration . getProperties ( ) . get ( configuration . getUsernameKey ( ) ) . toString ( ) ) ; } InternetAddress from = new InternetAddress ( item . getSender ( ) ) ; msg . setFrom ( from ) ; InternetAddress [ ] to = new InternetAddress [ item . getReceivers ( ) . size ( ) ] ; for ( int i = 0 ; i < item . getReceivers ( ) . size ( ) ; i ++ ) { to [ i ] = new InternetAddress ( item . getReceivers ( ) . get ( i ) ) ; } msg . setRecipients ( Message . RecipientType . TO , to ) ; msg . setSubject ( item . getTitle ( ) ) ; MimeBodyPart body = new MimeBodyPart ( ) ; body . setContent ( item . getBody ( ) , "text/html; charset=UTF-8" ) ; Multipart content = new MimeMultipart ( ) ; content . addBodyPart ( body ) ; if ( item . getAttachments ( ) != null && item . getAttachments ( ) . size ( ) > 0 ) { for ( DataSource attachment : item . getAttachments ( ) ) { BodyPart itemBodyPart = new MimeBodyPart ( ) ; itemBodyPart . setDataHandler ( new DataHandler ( attachment ) ) ; itemBodyPart . setFileName ( attachment . getName ( ) ) ; content . addBodyPart ( itemBodyPart ) ; } } msg . setContent ( content ) ; // update headers
msg . saveChanges ( ) ; Transport . send ( msg ) ; // set header value
for ( Map . Entry < String , String [ ] > entry : item . getHeaders ( ) . entrySet ( ) ) { String [ ] value = msg . getHeader ( entry . getKey ( ) ) ; if ( value != null ) { entry . setValue ( value ) ; } }


signature:
public class RobeHibernateBundle { /** * read more https : / / github . com / dropwizard / dropwizard / issues / 932
 * @ return Hibernate4Module */
@ Override protected Hibernate5Module createHibernate5Module ( ) { } }

implementation: Hibernate5Module module = new Hibernate5Module ( ) ; module . disable ( Hibernate5Module . Feature . USE_TRANSIENT_ANNOTATION ) ; return module ;


signature:
public class AbstractAuthResource { /** * Verify that the supplied password matches the password for this user . Password should
 * be stored as a hash . It is recommended you use the hashPassword ( password , accountName ) method
 * in this class .
 * This method is typically used for " reauthentication " for the most sensitive functions , such
 * as transactions , changing email address , and changing other account information .
 * @ param user the user who requires verification
 * @ param password the hashed user - supplied password
 * @ return true , if the password is correct for the specified user */
public boolean verifyPassword ( T user , String password ) { } }

implementation: Optional < T > entry ; entry = ( Optional < T > ) userStore . findByUsername ( user . getUsername ( ) ) ; return entry . isPresent ( ) && entry . get ( ) . getPassword ( ) . equals ( Hashing . sha256 ( ) . hashString ( password , Charset . forName ( "UTF-8" ) ) . toString ( ) ) ;


signature:
public class AbstractAuthResource { /** * Generate strong password that takes into account the user ' s information and old password . Implementations
 * should verify that the new password does not include information such as the username , fragments of the
 * old password , and other information that could be used to weaken the strength of the password .
 * @ param user the user whose information to use when generating password
 * @ param oldPassword the old password to use when verifying strength of new password . The new password may be checked for fragments of oldPassword .
 * @ return a password with strong password strength */
public String generateStrongPassword ( T user , String oldPassword ) { } }

implementation:
String newPassword ; do { newPassword = generateStrongPassword ( ) ; // Continue until new password does not contain user info or same with old password
} while ( newPassword . contains ( user . getUsername ( ) ) || oldPassword . equals ( Hashing . sha256 ( ) . hashString ( newPassword , Charset . forName ( "UTF-8" ) ) . toString ( ) ) ) ; return newPassword ;


signature:
public class AbstractAuthResource { /** * Changes the password for the specified user . This requires the current password , as well as
 * the password to replace it with . The new password should be checked against old hashes to be sure the new password does not closely resemble or equal any recent passwords for that UserEntry .
 * Password strength should also be verified . This new password must be repeated to ensure that the user has typed it in correctly .
 * @ param user the user to change the password for
 * @ param currentPassword the current password for the specified user
 * @ param newPassword the new password to use
 * @ param newPassword2 a verification copy of the new password
 * @ throws io . dropwizard . auth . AuthenticationException if any errors occur */
public void changePassword ( T user , String currentPassword , String newPassword , String newPassword2 ) throws AuthenticationException { } }

implementation: verifyPassword ( user , currentPassword ) ; if ( ! newPassword . equals ( newPassword2 ) ) { throw new AuthenticationException ( user . getUsername ( ) + ": New password and re-type password must be same" ) ; } else if ( newPassword . equals ( currentPassword ) ) { throw new AuthenticationException ( user . getUsername ( ) + ": New password and old password must be different" ) ; } verifyPasswordStrength ( currentPassword , newPassword , user ) ; Optional < ? extends UserEntry > optional = userStore . changePassword ( user . getUsername ( ) , newPassword ) ; if ( ! optional . isPresent ( ) ) { throw new AuthenticationException ( user . getUsername ( ) + ": Can't update UserEntry Password" ) ; }


signature:
public class AbstractAuthResource { /** * Returns the UserEntry matching the provided accountName . If the accoundId is not found , an Anonymous
 * UserEntry or null may be returned .
 * @ param accountName the account name
 * @ return the matching UserEntry object , or the Null UserEntry if no match exists */
public T getUser ( String accountName ) { } }

implementation: Optional < T > optional = ( Optional < T > ) userStore . findByUsername ( accountName ) ; if ( optional . isPresent ( ) ) { return optional . get ( ) ; } else { return null ; }


signature:
public class AbstractAuthResource { /** * Returns a string representation of the hashed password , using the
 * accountName as the salt . The salt helps to prevent against " rainbow "
 * table attacks where the attacker pre - calculates hashes for known strings .
 * This method specifies the use of the user ' s account name as the " salt "
 * value . The Encryptor . hash method can be used if a different salt is
 * required .
 * @ param password the password to hash
 * @ param accountName the account name to use as the salt
 * @ return the hashed password */
public String hashPassword ( String password , String accountName ) { } }

implementation: return Hashing . sha256 ( ) . hashString ( password , Charset . forName ( "UTF-8" ) ) . toString ( ) ;


signature:
public class AbstractAuthResource { /** * Ensures that the account name passes site - specific complexity requirements , like minimum length .
 * @ param accountName the account name
 * @ throws io . dropwizard . auth . AuthenticationException if account name does not meet complexity requirements */
public void verifyAccountNameStrength ( String accountName ) throws AuthenticationException { } }

implementation: Matcher matcher = PATTERN . matcher ( accountName ) ; if ( ! matcher . matches ( ) ) { throw new AuthenticationException ( accountName + " is not a valid email" ) ; }


signature:
public class AbstractAuthResource { /** * Ensures that the password meets site - specific complexity requirements , like length or number
 * of character sets . This method takes the old password so that the algorithm can analyze the
 * new password to see if it is too similar to the old password . Note that this has to be
 * invoked when the user has entered the old password , as the list of old
 * credentials stored by ESAPI is all hashed .
 * Additionally , the user object is taken in order to verify the password and account name differ .
 * @ param oldPassword the old password
 * @ param newPassword the new password
 * @ param user the user
 * @ throws io . dropwizard . auth . AuthenticationException if newPassword is too similar to oldPassword or if newPassword does not meet complexity requirements */
public void verifyPasswordStrength ( String oldPassword , String newPassword , T user ) throws AuthenticationException { } }

implementation: List < Rule > rules = getPasswordRules ( ) ; PasswordValidator validator = new PasswordValidator ( rules ) ; PasswordData passwordData = new PasswordData ( new Password ( newPassword ) ) ; RuleResult result = validator . validate ( passwordData ) ; if ( ! result . isValid ( ) ) { StringBuilder messages = new StringBuilder ( ) ; for ( String msg : validator . getMessages ( result ) ) { messages . append ( msg ) . append ( "\n" ) ; } throw new AuthenticationException ( messages . toString ( ) ) ; }


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

implementation: this . asset = new File ( path ) ; if ( ! this . asset . exists ( ) || ! this . asset . isFile ( ) ) throw new RuntimeException ( "File does not exist: " + path ) ;


signature:
public class FileAsset { /** * Generates hash ( MD5 ) from http path and last modification date */
public void generateMD5 ( ) { } }

implementation: md5 = Hashing . md5 ( ) . hashString ( asset . getPath ( ) + asset . lastModified ( ) , StandardCharsets . UTF_8 ) . toString ( ) ;


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

implementation: try { lastModified = asset . lastModified ( ) ; return Files . toByteArray ( asset ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; }


signature:
public class FileAsset { /** * Writes http to a cache ( byte array ) */
private void loadAssetToCache ( ) { } }

implementation: try { cache = com . google . common . io . Files . toByteArray ( asset ) ; lastModified = asset . lastModified ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; }


signature:
public class SystemParameterCache { /** * TODO this method should be refactoring . */
public static void fillCache ( ) { } }

implementation:
SessionFactory sessionFactory = RobeHibernateBundle . getInstance ( ) . getSessionFactory ( ) ; ManagedSessionContext . bind ( sessionFactory . openSession ( ) ) ; SystemParameterDao dao = new SystemParameterDao ( sessionFactory ) ; List < SystemParameter > parameters = dao . findAllStrict ( ) ; for ( SystemParameter parameter : parameters ) { cache . put ( parameter . getKey ( ) , parameter . getValue ( ) ) ; dao . detach ( parameter ) ; // TODO
}


signature:
public class SearchFactory { /** * implemented just to GET method .
 * @ return SearchModel */
@ Override public SearchModel provide ( ) { } }

implementation: SearchModel searchModel = new SearchModel ( ) ; searchModel . setResponse ( response ) ; String method = getMethod ( ) ; if ( "GET" . equals ( method ) ) { MultivaluedMap < String , String > queryParameters = getUriInfo ( ) . getQueryParameters ( ) ; for ( Map . Entry < String , List < String > > param : queryParameters . entrySet ( ) ) { if ( param . getValue ( ) . get ( 0 ) == null ) continue ; if ( "_q" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setQ ( param . getValue ( ) . get ( 0 ) ) ; } else if ( "_limit" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setLimit ( Integer . parseInt ( param . getValue ( ) . get ( 0 ) ) ) ; } else if ( "_offset" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setOffset ( Integer . parseInt ( param . getValue ( ) . get ( 0 ) ) ) ; } else if ( "_fields" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setFields ( param . getValue ( ) . get ( 0 ) . split ( "," ) ) ; } else if ( "_sort" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setSort ( param . getValue ( ) . get ( 0 ) . split ( "," ) ) ; } else if ( "_filter" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setFilterExpression ( param . getValue ( ) . get ( 0 ) ) ; } } } return searchModel ;


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

implementation: try { if ( configuration . getGuice ( ) == null ) { LOGGER . error ( "GuiceBundle can not work without and configuration!" ) ; } GuiceBundle . configuration = configuration . getGuice ( ) ; createReflections ( configuration . getGuice ( ) . getScanPackages ( ) ) ; JerseyUtil . registerGuiceBound ( injector , environment . jersey ( ) ) ; JerseyUtil . registerGuiceFilter ( environment ) ; deModule . setEnvironmentData ( configuration , environment ) ; findAndRunScanners ( environment , injector ) ; } catch ( Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; }


signature:
public class GuiceBundle { /** * Creates a { @ link org . reflections . Reflections } with the given packages ( configuration )
 * @ param scanPackages */
private void createReflections ( String [ ] scanPackages ) { } }

implementation: if ( scanPackages . length < 1 ) { LOGGER . warn ( "No package defined in configuration (scanPackages)!" ) ; return ; } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder ( ) ; FilterBuilder filterBuilder = new FilterBuilder ( ) ; for ( String packageName : scanPackages ) { configurationBuilder . addUrls ( ClasspathHelper . forPackage ( packageName ) ) ; filterBuilder . include ( FilterBuilder . prefix ( packageName ) ) ; } configurationBuilder . filterInputsBy ( filterBuilder ) . setScanners ( new SubTypesScanner ( ) , new TypeAnnotationsScanner ( ) ) ; this . reflections = new Reflections ( configurationBuilder ) ;


signature:
public class GuiceBundle { /** * Collects all classes extended { @ link io . robe . guice . scanner . Scanner } and adds them to environment
 * @ param environment target environment
 * @ param injector guice injector to create instances . */
private void findAndRunScanners ( Environment environment , Injector injector ) { } }

implementation: Set < Class < ? extends Scanner > > scanners = reflections . getSubTypesOf ( Scanner . class ) ; for ( Class < ? extends Scanner > scanner : scanners ) { try { LOGGER . info ( scanner . getName ( ) + ": " ) ; Scanner instance = scanner . newInstance ( ) ; instance . scanAndAdd ( environment , injector , reflections ) ; } catch ( Exception e ) { LOGGER . error ( "Added scanner: " + scanner , e ) ; } }


signature:
public class Transaction { /** * Begins new transaction in a new session and performs operations provided in { @ link TransactionWrapper } < br / >
 * In case of an exception is thrown the { @ link TransactionExceptionHandler } will be invoked .
 * @ param transactionWrapper { @ link TransactionWrapper }
 * @ param exceptionHandler { @ link TransactionExceptionHandler } */
public static void exec ( TransactionWrapper transactionWrapper , TransactionExceptionHandler exceptionHandler ) { } }

implementation: exec ( transactionWrapper , exceptionHandler , FlushMode . AUTO ) ;


signature:
public class Transaction { /** * Begins new transaction in a new session and performs operations provided in { @ link TransactionWrapper } < br / >
 * In case of an exception is thrown the { @ link TransactionExceptionHandler } will be invoked .
 * @ param transactionWrapper { @ link TransactionWrapper }
 * @ param exceptionHandler { @ link TransactionExceptionHandler }
 * @ param flushMode { @ link FlushMode } */
public static void exec ( TransactionWrapper transactionWrapper , TransactionExceptionHandler exceptionHandler , FlushMode flushMode ) { } }

implementation: checkNotNull ( transactionWrapper ) ; new Transaction ( transactionWrapper , exceptionHandler , flushMode ) ;


signature:
public class Transaction { /** * If present , backup current the session in { @ link ManagedSessionContext } and unbinds it . */
private void storePreviousSession ( ) { } }

implementation: if ( ManagedSessionContext . hasBind ( SESSION_FACTORY ) ) { SESSIONS . get ( ) . add ( SESSION_FACTORY . getCurrentSession ( ) ) ; ManagedSessionContext . unbind ( SESSION_FACTORY ) ; }


signature:
public class Transaction { /** * Opens a new session , sets flush mode and bind this session to { @ link ManagedSessionContext } */
private void configureNewSession ( ) { } }

implementation: session = SESSION_FACTORY . openSession ( ) ; session . setFlushMode ( flushMode ) ; ManagedSessionContext . bind ( session ) ;


signature:
public class Transaction { /** * If transaction is present and active then commit . */
private void success ( ) { } }

implementation: org . hibernate . Transaction txn = session . getTransaction ( ) ; if ( txn != null && txn . getStatus ( ) . equals ( TransactionStatus . ACTIVE ) ) { txn . commit ( ) ; }


signature:
public class Transaction { /** * If transaction is present and active then rollback . */
private void error ( ) { } }

implementation: org . hibernate . Transaction txn = session . getTransaction ( ) ; if ( txn != null && txn . getStatus ( ) . equals ( TransactionStatus . ACTIVE ) ) { txn . rollback ( ) ; }


signature:
public class Transaction { /** * Closes and unbinds the current session . < br / >
 * If { @ link ManagedSessionContext } had a session before the current session , re - binds it to { @ link ManagedSessionContext } */
private void finish ( ) { } }

implementation: try { if ( session != null ) { session . close ( ) ; } } finally { ManagedSessionContext . unbind ( SESSION_FACTORY ) ; if ( ! SESSIONS . get ( ) . isEmpty ( ) ) { ManagedSessionContext . bind ( SESSIONS . get ( ) . pop ( ) ) ; } }


signature:
public class Transaction { /** * Starts the progress . */
private void start ( ) { } }

implementation: try { before ( ) ; transactionWrapper . wrap ( ) ; success ( ) ; } catch ( Exception e ) { error ( ) ; if ( exceptionHandler != null ) { exceptionHandler . onException ( e ) ; } else { throw e ; } } finally { finish ( ) ; }


signature:
public class PermissionResource { /** * get hierarchical menu service for permission
 * @ param credentials Injected by { @ link RobeAuth } annotation for authentication .
 * @ return collection of hierarchical { @ link MenuItem } */
@ RobeService ( group = "Permission" , description = "Get hierarchical menu service for permission" ) @ Path ( "menus" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public List < MenuItem > getHierarchicalMenu ( @ RobeAuth Credentials credentials ) { } }

implementation: return readMenuHierarchical ( convertMenuToMenuItem ( menuDao . findHierarchicalMenu ( ) ) ) ;


signature:
public class PermissionResource { /** * Return all { @ link Permission } s as a collection .
 * @ param credentials Injected by @ { @ link RobeAuth } annotation for authentication .
 * @ return all @ { @ link Permission } s as a collection . */
@ RobeService ( group = "Permission" , description = "Return all permissions as a collection." ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public List < Permission > getAll ( @ RobeAuth Credentials credentials , @ SearchParam SearchModel search ) { } }

implementation: return permissionDao . findAllStrict ( search ) ;


signature:
public class PermissionResource { /** * Creates a { @ link Permission } resource .
 * Status Code :
 * Not Found 404
 * Not Matches 412
 * @ param credentials Injected by @ { @ link RobeAuth } annotation for authentication .
 * @ param model Data of { @ link Permission }
 * @ return Creates a @ { @ link Permission } resource . */
@ RobeService ( group = "Permission" , description = "Creates a permission resource." ) @ POST @ UnitOfWork public Permission create ( @ RobeAuth Credentials credentials , @ Valid Permission model ) { } }

implementation: return permissionDao . create ( model ) ;


signature:
public class Query { /** * roleOid . permissionOid . code */
public static < E > Holder < E > configureFieldByName ( Criteria < E > criteria , String name ) { } }

implementation:
if ( Validations . isEmptyOrNull ( name ) ) return null ; // parse x . y name as [ x , y ]
String [ ] names = name . split ( "\\." ) ; // uses to keep current name by names index .
String currentName ; // init start index of names .
int step = 0 ; // always will be current criteria
CriteriaParent < E > currentCriteria = criteria ; FieldMeta currentFieldMeta ; // use aliasJoiner to use as alias .
StringJoiner aliasJoiner = new StringJoiner ( "$" ) ; do { // get current name of field by index . like x . y . z = > if step = 1 then currentName = y
currentName = names [ step ] ; if ( Validations . isEmptyOrNull ( currentName ) ) { throw new RuntimeException ( currentName + " defined name is wrong ! " ) ; } currentFieldMeta = criteria . getMeta ( ) . getFieldMap ( ) . get ( currentName ) ; step ++ ; aliasJoiner . add ( currentCriteria . getAlias ( ) ) ; if ( step >= names . length ) { break ; } if ( currentFieldMeta . getReference ( ) == null ) { throw new RuntimeException ( "" + currentName + " join field of " + name + "'s reference target information must defined ! " ) ; } CriteriaJoin < E > criteriaJoin = currentCriteria . getJoin ( currentName ) ; if ( criteriaJoin == null ) { currentCriteria . createJoin ( currentName , currentFieldMeta . getReference ( ) . getTargetEntity ( ) , currentFieldMeta . getReference ( ) . getReferenceId ( ) ) ; } currentCriteria = criteriaJoin ; } while ( step >= names . length ) ; Holder < E > holder = new Holder < > ( ) ; holder . currentFieldName = currentName ; holder . currentCriteria = currentCriteria ; holder . currentFieldMeta = currentFieldMeta ; return holder ;


signature:
public class TokenFactory { /** * Merges all path patterns and and creates a single string value which will be equal with service methods path
 * annotation value and HTTP method type . Generated string will be used for permission checks .
 * @ param token for checking permission list
 * @ param matchedTemplates matched templates of context . They will be merged with reverse order
 * @ param method HTTP Method of the request . Will be merged with
 * @ return true if user is Authorized . */
private boolean isAuthorized ( BasicToken token , List < UriTemplate > matchedTemplates , String method ) { } }

implementation:
StringBuilder path = new StringBuilder ( ) ; // Merge all path templates and generate a path .
for ( UriTemplate template : matchedTemplates ) { path . insert ( 0 , template . getTemplate ( ) ) ; } path . append ( ":" ) . append ( method ) ; // Look at user permissions to see if the service is permitted .
return token . getPermissions ( ) . contains ( path . toString ( ) ) ;


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

implementation: this . configuration = configuration . getAuth ( ) ; environment . jersey ( ) . register ( new TokenFactoryProvider . Binder < Credentials > ( Credentials . class ) ) ; environment . jersey ( ) . register ( new TokenBasedAuthResponseFilter ( configuration . getAuth ( ) ) ) ; environment . jersey ( ) . register ( TokenFeature . class ) ; BasicToken . configure ( configuration . getAuth ( ) ) ; if ( configuration . getAuth ( ) . getAlgorithm ( ) != null ) { checkCryptography ( this . configuration ) ; } environment . jersey ( ) . register ( new SecurityHeadersFilter ( configuration . getAuth ( ) ) ) ;


signature:
public class TokenAuthBundle { /** * Determines if cryptography restrictions apply .
 * Restrictions apply if the value of { @ link Cipher # getMaxAllowedKeyLength ( String ) } returns a value smaller than { @ link Integer # MAX _ VALUE } if there are any restrictions according to the JavaDoc of the method .
 * This method is used with the transform < code > " AES / CBC / PKCS5Padding " < / code > as this is an often used algorithm that is < a href = " https : / / docs . oracle . com / javase / 8 / docs / technotes / guides / security / StandardNames . html # impl " > an implementation requirement for Java SE < / a > .
 * @ return < code > true < / code > if restrictions apply , < code > false < / code > otherwise */
public static void checkCryptography ( TokenBasedAuthConfiguration configuration ) { } }

implementation: try { Field field = Class . forName ( "javax.crypto.JceSecurity" ) . getDeclaredField ( "isRestricted" ) ; field . setAccessible ( true ) ; field . set ( null , java . lang . Boolean . FALSE ) ; } catch ( ClassNotFoundException e ) { StringBuilder builder = new StringBuilder ( "javax.crypto.JceSecurity class not found !\n" ) ; builder . append ( getUpgradJceErrorMessage ( ) ) ; throw new RuntimeException ( builder . toString ( ) , e ) ; } catch ( final IllegalAccessException | NoSuchFieldException e ) { try { if ( BasicToken . getEncryptor ( ) . isInitialized ( ) ) { BasicToken . getEncryptor ( ) . encrypt ( "Sample Data" ) ; } } catch ( EncryptionOperationNotPossibleException ex ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( configuration . getAlgorithm ( ) ) . append ( " not exist on Java Cryptography Extension (JCE)" ) . append ( getUpgradJceErrorMessage ( ) ) ; LOGGER . error ( builder . toString ( ) ) ; throw new RuntimeException ( builder . toString ( ) , ex ) ; } }


signature:
public class SystemParameterResource { /** * Create { @ link SystemParameter ) resource .
 * @ param credentials Injected by { @ link RobeAuth } annotation for authentication .
 * @ param model This is the one model of { @ link SystemParameter }
 * @ return Create { @ link SystemParameter ) resource and return given SystemParameter path link at header Location = example / { id ] . */
@ RobeService ( group = "SystemParameter" , description = "Create SystemParameter resource and return given SystemParameter path link at header Location=example/{id]." ) @ POST @ UnitOfWork public SystemParameter create ( @ RobeAuth Credentials credentials , @ Valid SystemParameter model ) { } }

implementation: return systemParameterDao . create ( model ) ;


signature:
public class SystemParameterResource { /** * Create or update { @ link SystemParameter ) resource .
 * @ param credentials Injected by { @ link RobeAuth } annotation for authentication .
 * @ param model This is the one model of { @ link SystemParameter }
 * @ return Create { @ link SystemParameter ) resource and return given SystemParameter path link at header Location = example / { id ] . */
@ RobeService ( group = "SystemParameter" , description = "Create or update SystemParameter resource." ) @ POST @ Path ( "admin" ) @ UnitOfWork public Map < String , String > bulkSaveOrUpdate ( Map < String , String > values ) { } }

implementation: for ( Map . Entry < String , String > entry : values . entrySet ( ) ) { Optional < SystemParameter > optionalParameter = systemParameterDao . findByKey ( entry . getKey ( ) ) ; SystemParameter parameter ; if ( ! optionalParameter . isPresent ( ) ) { parameter = new SystemParameter ( ) ; parameter . setKey ( entry . getKey ( ) ) ; parameter . setValue ( entry . getValue ( ) ) ; } else { parameter = optionalParameter . get ( ) ; parameter . setValue ( entry . getValue ( ) ) ; } systemParameterDao . update ( parameter ) ; } return values ;


signature:
public class ParseDate { /** * First it checks is there any annotation class for parsing operations ,
 * if it is , parses with given format , if there is a exception while
 * parsing with given format catches and tries with default values ,
 * If there is no given format , tries with static values
 * @ param o Object from cell value
 * @ param field Field from given pojo
 * @ return Valid date after parsing with pattern */
@ Override public Date parse ( Object o , Field field ) { } }

implementation: if ( ! isValid ( o ) ) { return null ; } JsonFormat formatAnn = field . getAnnotation ( JsonFormat . class ) ; if ( formatAnn == null ) { throw new RuntimeException ( "JsonFormat with pattern needed for: " + field . getName ( ) ) ; } try { return new SimpleDateFormat ( formatAnn . pattern ( ) , Locale . getDefault ( ) ) . parse ( o . toString ( ) ) ; } catch ( ParseException e ) { throw new RuntimeException ( "JsonFormat with pattern is wrong for: " + field . getName ( ) + " pattern: " + formatAnn . pattern ( ) ) ; }


signature:
public class RobeRuntimeException { /** * Gets current response created with exception parameters .
 * @ return current response */
public Response getResponse ( ) { } }

implementation: return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( builder . build ( ) ) . build ( ) ;


signature:
public class Restrictions { /** * generates ' = ' equals
 * @ param name
 * variableAlias
 * @ return */
public static Restriction eq ( String name , Object value ) { } }

implementation: return new Restriction ( Operator . EQUALS , name , value ) ;


signature:
public class Restrictions { /** * ' ! = ' not equals operator */
public static Restriction ne ( String name , Object value ) { } }

implementation: return new Restriction ( Operator . NOT_EQUALS , name , value ) ;


signature:
public class Restrictions { /** * ' < ' less than operator */
public static Restriction lt ( String name , Object Object ) { } }

implementation: return new Restriction ( Operator . LESS_THAN , name , Object ) ;


signature:
public class Restrictions { /** * ' < = ' less or equals than operator */
public static Restriction le ( String name , Object value ) { } }

implementation: return new Restriction ( Operator . LESS_OR_EQUALS_THAN , name , value ) ;


signature:
public class Restrictions { /** * ' > ' greater than operator */
public static Restriction gt ( String name , Object value ) { } }

implementation: return new Restriction ( Operator . GREATER_THAN , name , value ) ;


signature:
public class Restrictions { /** * ' > = ' greater or equals than operator */
public static Restriction ge ( String name , Object value ) { } }

implementation: return new Restriction ( Operator . GREATER_OR_EQUALS_THAN , name , value ) ;


signature:
public class Restrictions { /** * ' ~ = ' contains than operator */
public static Restriction ilike ( String name , Object value ) { } }

implementation: return new Restriction ( Operator . CONTAINS , name , value ) ;


signature:
public class Restrictions { /** * ' | = ' in list operator */
public static Restriction in ( String name , Object value ) { } }

implementation: return new Restriction ( Operator . IN , name , value ) ;


signature:
public class NamespaceManager { /** * Update the list of declared namespaces with a new namespace .
 * @ param namespace Namespace curie identifier
 * @ param href Namesapce URL
 * @ return A new instance of the namespace manager with the additional namespace . */
public NamespaceManager withNamespace ( String namespace , String href ) { } }

implementation: if ( namespaces . containsKey ( namespace ) ) { throw new RepresentationException ( format ( "Duplicate namespace '%s' found for representation factory" , namespace ) ) ; } if ( ! href . contains ( "{rel}" ) ) { throw new RepresentationException ( format ( "Namespace '%s' does not include {rel} URI template argument." , namespace ) ) ; } return new NamespaceManager ( namespaces . put ( namespace , href ) ) ;


signature:
public class ResourceRepresentation { /** * Adds or replaces the content of the representation .
 * @ param content The source content of the representation .
 * @ return A new instance of a PersistentRepresentation with the namespace included . */
public ResourceRepresentation < V > withContent ( ByteString content ) { } }

implementation: return new ResourceRepresentation < > ( Option . of ( content ) , links , rels , namespaceManager , value , resources ) ;


signature:
public class ResourceRepresentation { /** * Define rel semantics for this representation .
 * @ param rel A defined relationship type */
public ResourceRepresentation < V > withRel ( Rel rel ) { } }

implementation: if ( rels . containsKey ( rel . rel ( ) ) ) { throw new IllegalStateException ( String . format ( "Rel %s is already declared." , rel . rel ( ) ) ) ; } final TreeMap < String , Rel > updatedRels = rels . put ( rel . rel ( ) , rel ) ; return new ResourceRepresentation < > ( content , links , updatedRels , namespaceManager , value , resources ) ;


signature:
public class ResourceRepresentation { /** * Add a link to this resource .
 * @ param rel
 * @ param uri The target URI for the link , possibly relative to the href of this resource .
 * @ return */
public ResourceRepresentation < V > withLink ( String rel , URI uri ) { } }

implementation: return withLink ( rel , uri . toASCIIString ( ) ) ;


signature:
public class ResourceRepresentation { /** * Add a link to this resource .
 * @ param rel
 * @ param href The target href for the link , relative to the href of this resource .
 * @ param properties The properties to add to this link object */
public ResourceRepresentation < V > withLink ( String rel , String href , Map < String , String > properties ) { } }

implementation: return withLink ( Links . create ( rel , href , properties ) ) ;


signature:
public class ResourceRepresentation { /** * Add a link to this resource .
 * @ param rel
 * @ param href The target href for the link , relative to the href of this resource .
 * @ param properties The properties to add to this link object */
public ResourceRepresentation < V > withLink ( String rel , String href , java . util . Map < String , String > properties ) { } }

implementation: return withLink ( Links . create ( rel , href , HashMap . ofAll ( properties ) ) ) ;


signature:
public class ResourceRepresentation { /** * Add a link to this resource .
 * @ param link The target link */
public ResourceRepresentation < V > withLink ( Link link ) { } }

implementation: String rel = Links . getRel ( link ) ; Support . checkRelType ( rel ) ; validateSingletonRel ( rel ) ; final TreeMap < String , Rel > updatedRels = ! rels . containsKey ( rel ) ? rels . put ( rel , Rels . natural ( rel ) ) : rels ; final List < Link > updatedLinks = links . append ( link ) ; return new ResourceRepresentation < > ( content , updatedLinks , updatedRels , namespaceManager , value , resources ) ;


signature:
public class ResourceRepresentation { /** * Add a link to this resource .
 * @ param links The target link */
public ResourceRepresentation < V > withLinks ( List < Link > links ) { } }

implementation: links . forEach ( link -> { String rel = Links . getRel ( link ) ; Support . checkRelType ( rel ) ; validateSingletonRel ( rel ) ; } ) ; final TreeMap < String , Rel > updatedRels = links . map ( Links :: getRel ) . foldLeft ( rels , ( accum , rel ) -> ! accum . containsKey ( rel ) ? accum . put ( rel , Rels . natural ( rel ) ) : accum ) ; final List < Link > updatedLinks = this . links . appendAll ( links ) ; return new ResourceRepresentation < > ( content , updatedLinks , updatedRels , namespaceManager , value , resources ) ;


signature:
public class ResourceRepresentation { /** * Replace the value of this resource with a new value , optionally of a new type .
 * @ param newValue The new value for this resource
 * @ param < R > The type of the new value
 * @ return The new resource */
public < R > ResourceRepresentation < R > withValue ( R newValue ) { } }

implementation: return new ResourceRepresentation < > ( Option . none ( ) , links , rels , namespaceManager , newValue , resources ) ;


signature:
public class ResourceRepresentation { /** * Adds a new namespace .
 * @ param namespace The CURIE prefix for the namespace being added .
 * @ param href The target href of the namespace being added . This may be relative to the
 * resourceFactories baseref
 * @ return A new instance of a PersistentRepresentation with the namespace included . */
public ResourceRepresentation < V > withNamespace ( String namespace , String href ) { } }

implementation: if ( ! rels . containsKey ( "curies" ) ) { rels = rels . put ( "curies" , Rels . collection ( "curies" ) ) ; } final NamespaceManager updatedNamespaceManager = namespaceManager . withNamespace ( namespace , href ) ; return new ResourceRepresentation < > ( content , links , rels , updatedNamespaceManager , value , resources ) ;


signature:
public class ImmutableMap { /** * Creates a new { @ code ImmutableSet } from the given { @ code Iterable } .
 * @ param < K > the type of the { @ code Map } ' s keys .
 * @ param < V > the type of the { @ code Map } ' s values .
 * @ param map the source { @ code Map } .
 * @ return the created { @ code ImmutableMap } .
 * @ throws NullPointerException if { @ code map } is { @ code null } . */
public static < K , V > Map < K , V > copyOf ( Map < ? extends K , ? extends V > map ) { } }

implementation: return new ImmutableMap < K , V > ( new LinkedHashMap < K , V > ( map ) ) ;


signature:
public class Throwables { /** * Returns the root cause of the given { @ code Throwable } . If the given
 * { @ code Throwable } is not the result of a previous one , it is
 * considered as the root .
 * @ param t the { @ code Throwable } to get the root cause .
 * @ return the root cause of the given { @ code Throwable } .
 * @ throws NullPointerException if { @ code t } is { @ code null } . */
public static Throwable getRootCause ( Throwable t ) { } }

implementation: Throwable cause = t . getCause ( ) ; return cause == null ? t : getRootCause ( cause ) ;


signature:
public class Throwables { /** * Returns the chain of { @ code Throwable } s that caused the given one .
 * The given { @ code Throwable } is the first element in the returned
 * { @ code List } , the last one is the root cause .
 * @ param t the { @ code Throwable } to get the chain .
 * @ return the chain of { @ code Throwable } that caused { @ code t } .
 * @ throws NullPointerException if { @ code t } is { @ code null } . */
public static List < Throwable > getCauseChain ( Throwable t ) { } }

implementation: List < Throwable > chain = new ArrayList < Throwable > ( ) ; chain . add ( Parameters . checkNotNull ( t ) ) ; Throwable cause = t . getCause ( ) ; while ( cause != null ) { chain . add ( cause ) ; cause = cause . getCause ( ) ; } return Collections . unmodifiableList ( chain ) ;


signature:
public class Throwables { /** * Returns the stack trace of the given { @ code Throwable } as a
 * { @ code String } .
 * @ param t the { @ code Throwable } to get the stack trace .
 * @ return the stack trace of the given { @ code Throwable } .
 * @ throws NullPointerException if { @ code t } is { @ code null } . */
public static String getStackTrace ( Throwable t ) { } }

implementation: StringWriter out = new StringWriter ( ) ; PrintWriter writer = new PrintWriter ( out ) ; t . printStackTrace ( writer ) ; writer . flush ( ) ; return out . toString ( ) ;


signature:
public class Throwables { /** * Returns the stack frames of the given { @ code Throwable } . The stack
 * frames are simply obtained from calling { @ code toString } on each
 * { @ link StackTraceElement } of { @ code t } .
 * @ param t the { @ code Throwable } to get the stack frames .
 * @ return the stack frames of the given { @ code Throwable } .
 * @ throws NullPointerException if { @ code t } is { @ code null } .
 * @ see Throwable # getStackTrace ( ) */
public static List < String > getStackFrames ( Throwable t ) { } }

implementation: StackTraceElement [ ] elements = t . getStackTrace ( ) ; List < String > frames = new ArrayList < String > ( elements . length ) ; for ( StackTraceElement element : elements ) { frames . add ( element . toString ( ) ) ; } return Collections . unmodifiableList ( frames ) ;


signature:
public class Throwables { /** * Re - throws the given { @ code Throwable } if it is already an instance of
 * { @ code RuntimeException } or { @ link Error } , and , if not , wraps it in a
 * { @ code RuntimeException } before throwing it .
 * @ param t the { @ code Throwable } to propagate .
 * @ return nothing ( this method always throws a { @ code Throwable } ) .
 * @ throws NullPointerException if { @ code t } is { @ code null } .
 * @ throws RuntimeException if { @ code t } is already an instance of
 * { @ code RuntimeException } or if { @ code t } is neither an instance
 * of { @ code RuntimeException } nor an instance of { @ code Error } .
 * @ throws Error if { @ code t } is an instance of { @ code Error } . */
public static RuntimeException propagate ( Throwable t ) { } }

implementation: Parameters . checkNotNull ( t ) ; if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error ) t ; } throw new RuntimeException ( t ) ;


signature:
public class ObjectCodec { /** * Serializes the given { @ code Serializable } object into an array of
 * { @ code byte } s .
 * @ param object the object to encode .
 * @ return the given object ' s encoding .
 * @ throws NullPointerException if { @ code object } is { @ code null } .
 * @ throws EncodingException if the given object cannot be serialized . */
public static byte [ ] encode ( Serializable object ) { } }

implementation: Parameters . checkNotNull ( object ) ; ObjectOutputStream oos = null ; try { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; oos = new ObjectOutputStream ( out ) ; oos . writeObject ( object ) ; oos . flush ( ) ; return out . toByteArray ( ) ; } catch ( IOException ex ) { throw new EncodingException ( ex ) ; } finally { IO . close ( oos ) ; }


signature:
public class ObjectCodec { /** * Deserializes the given array of { @ code byte } s into an object .
 * @ param < T > the object ' s expected type .
 * @ param bytes the object ' s encoding .
 * @ param t the object ' s expected type ' s { @ code Class } .
 * @ return the deserialized object .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws DecodingException if the deserialization fails .
 * @ throws ClassCastException if the deserialized object is not an
 * instance of the expected class . */
public static < T extends Serializable > T decode ( byte [ ] bytes , Class < T > t ) { } }

implementation: Parameters . checkNotNull ( t ) ; Parameters . checkNotNull ( bytes ) ; ObjectInputStream ois = null ; ByteArrayInputStream in = new ByteArrayInputStream ( bytes ) ; try { ois = new ObjectInputStream ( in ) ; return Parameters . checkType ( ois . readObject ( ) , t ) ; } catch ( IOException ex ) { throw new DecodingException ( ex ) ; } catch ( ClassNotFoundException ex ) { throw new DecodingException ( ex ) ; } finally { IO . close ( ois ) ; }


signature:
public class UTF8 { /** * Returns whether the specified range in the given { @ code String } can
 * be encoded into UTF - 8.
 * @ param str the input { @ code String } .
 * @ param off the start index , inclusive .
 * @ param len the number of characters to test .
 * @ return whether the specified range in { @ code str } can be encoded
 * into UTF - 8.
 * @ throws NullPointerException if { @ code str } is { @ code null } .
 * @ throws IndexOutOfBoundsException if { @ code off } or { @ code len } is
 * negative or if { @ code off + len } is greater than { @ code str } ' s
 * length . */
public static boolean canEncode ( String str , int off , int len ) { } }

implementation: return canEncode ( str . substring ( off , off + len ) ) ;


signature:
public class UTF8 { /** * Returns whether the specified range in the given byte array represents
 * valid UTF - 8 encoded characters .
 * @ param input the input buffer .
 * @ param off the start index , inclusive .
 * @ param len the number of bytes to test .
 * @ return whether the specified range in { @ code input } represents UTF - 8
 * encoded characters .
 * @ throws NullPointerException if { @ code input } is { @ code null } .
 * @ throws IndexOutOfBoundsException if { @ code off } or { @ code len } is
 * negative or if { @ code off + len } is greater than { @ code input } ' s
 * length . */
public static boolean canDecode ( byte [ ] input , int off , int len ) { } }

implementation: try { decode ( input , off , len ) ; } catch ( IllegalArgumentException ex ) { return false ; } return true ;


signature:
public class UTF8 { /** * Returns the UTF - 8 encoding of the given { @ code String } .
 * @ param str the { @ code String } to encode .
 * @ return the UTF - 8 encoding of the given { @ code String } .
 * @ throws NullPointerException if { @ code str } is { @ code null } .
 * @ throws IllegalArgumentException if { @ code str } can ' t be encoded into
 * UTF - 8. */
public static byte [ ] encode ( String str ) { } }

implementation: CharsetEncoder encoder = Charsets . UTF_8 . newEncoder ( ) ; try { ByteBuffer out = encoder . encode ( CharBuffer . wrap ( str ) ) ; byte [ ] bytes = new byte [ out . limit ( ) ] ; out . get ( bytes ) ; return bytes ; } catch ( CharacterCodingException ex ) { throw new IllegalArgumentException ( ex ) ; }


signature:
public class UTF8 { /** * Returns the UTF - 8 encoding of the specified character sequence .
 * @ param str the input { @ code String } .
 * @ param off the start index , inclusive .
 * @ param len the number of characters to encode .
 * @ return the UTF - 8 encoding of the specified characters .
 * @ throws NullPointerException if { @ code str } is { @ code null } .
 * @ throws IndexOutOfBoundsException if { @ code off } or { @ code len } is
 * negative or if { @ code off + len } is greater than { @ code str } ' s
 * length .
 * @ throws IllegalArgumentException if { @ code str } can ' t be encoded into
 * UTF - 8. */
public static byte [ ] encode ( String str , int off , int len ) { } }

implementation: return encode ( str . substring ( off , off + len ) ) ;


signature:
public class LittleEndian { /** * Encodes the given { @ code int } value using little - endian byte ordering
 * convention into the given array , starting at the given offset .
 * @ param n the { @ code int } value to encode .
 * @ param out the output buffer .
 * @ param off the output offset .
 * @ throws NullPointerException if { @ code out } is { @ code null } .
 * @ throws IndexOutOfBoundsException if { @ code off } is negative or if
 * { @ code out } ' s length is lower than { @ code off + 4 } . */
public static void encode ( int n , byte [ ] out , int off ) { } }


signature:
public class LittleEndian { /** * Encodes the given { @ code long } value using little - endian byte
 * ordering convention into the given array , starting at the given
 * offset .
 * @ param n the { @ code long } value to encode .
 * @ param out the output buffer .
 * @ param off the output offset .
 * @ throws NullPointerException if { @ code out } is { @ code null } .
 * @ throws IndexOutOfBoundsException if { @ code off } is negative or if
 * { @ code out } ' s length is lower than { @ code off + 8 } . */
public static void encode ( long n , byte [ ] out , int off ) { } }


signature:
public class LittleEndian { /** * Decodes the first 4 bytes starting at { @ code off } of the given array
 * into an { @ code int } value using little - endian byte ordering
 * convention .
 * @ param in the encoded value .
 * @ param off the input offset .
 * @ return the decoded { @ code int } value .
 * @ throws NullPointerException if { @ code in } is { @ code null } .
 * @ throws IndexOutOfBoundsException if { @ code off } is negative or if
 * { @ code in } ' s length is lower than { @ code off + 4 } . */
public static int decodeInt ( byte [ ] in , int off ) { } }


signature:
public class LittleEndian { /** * Decodes the first 8 bytes starting at { @ code off } of the given array
 * into a { @ code long } value using little - endian byte ordering
 * convention .
 * @ param in the encoded value .
 * @ param off the input offset .
 * @ return the decoded { @ code long } value .
 * @ throws NullPointerException if { @ code in } is { @ code null } .
 * @ throws IndexOutOfBoundsException if { @ code off } is negative or if
 * { @ code in } ' s length is lower than { @ code off + 8 } . */
public static long decodeLong ( byte [ ] in , int off ) { } }


signature:
public class CharStreams { /** * Copies the content of the given { @ code InputStream } into the given
 * { @ code Writer } using the system ' s default charset .
 * @ param in the { @ code InputStream } to read from .
 * @ param out the { @ code Reader } to write on .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if an I / O error occurs during the process . */
public static void copy ( InputStream in , Writer out ) throws IOException { } }

implementation: copy ( new InputStreamReader ( in , Charsets . DEFAULT ) , out ) ;


signature:
public class CharStreams { /** * Copies the content of the given { @ code InputStream } into the given
 * { @ code Writer } using the specified charset .
 * @ param in the { @ code InputStream } to read from .
 * @ param out the { @ code Reader } to write on .
 * @ param charset the charset to use .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if an I / O error occurs during the process . */
public static void copy ( InputStream in , Writer out , Charset charset ) throws IOException { } }

implementation: copy ( new InputStreamReader ( in , charset ) , out ) ;


signature:
public class CharStreams { /** * Copies the content of the given { @ code Reader } into the given
 * { @ code OutputStream } using the system ' s default charset .
 * @ param in the { @ code Reader } to read from .
 * @ param out the { @ code OutputStream } to write on .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if an I / O error occurs during the process . */
public static void copy ( Reader in , OutputStream out ) throws IOException { } }

implementation: copy ( in , new OutputStreamWriter ( out , Charsets . DEFAULT ) ) ;


signature:
public class CharStreams { /** * Copies the content of the given { @ code Reader } into the given
 * { @ code OutputStream } using the specified charset .
 * @ param in the { @ code Reader } to read from .
 * @ param out the { @ code OutputStream } to write on .
 * @ param charset the charset to use .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if an I / O error occurs during the process . */
public static void copy ( Reader in , OutputStream out , Charset charset ) throws IOException { } }

implementation: copy ( in , new OutputStreamWriter ( out , charset ) ) ;


signature:
public class CharStreams { /** * Returns whether the given streams have the same content .
 * @ param in1 the first stream .
 * @ param in2 the second stream .
 * @ return { @ code true } if the streams have the same content .
 * @ throws IOException if an I / O error occurs during the process . */
public static boolean equal ( Reader in1 , Reader in2 ) throws IOException { } }

implementation: if ( in1 == in2 ) { return true ; } if ( in1 == null || in2 == null ) { return false ; } in1 = buffer ( in1 ) ; in2 = buffer ( in2 ) ; int c1 = in1 . read ( ) ; int c2 = in2 . read ( ) ; while ( c1 != - 1 && c2 != - 1 && c1 == c2 ) { c1 = in1 . read ( ) ; c2 = in2 . read ( ) ; } return in1 . read ( ) == - 1 && in2 . read ( ) == - 1 ;


signature:
public class CharStreams { /** * Reads the whole content of the given { @ code Reader } into a
 * { @ code String } .
 * @ param in the stream to read .
 * @ return the stream ' s content as a { @ code String } .
 * @ throws NullPointerException if { @ code in } is { @ code null } .
 * @ throws IOException if the stream cannot be read . */
public static String read ( Reader in ) throws IOException { } }

implementation: Writer out = new StringWriter ( ) ; copy ( in , out ) ; return out . toString ( ) ;


signature:
public class CharStreams { /** * Reads the whole content of the given { @ code InputStream } into a
 * { @ code String } using the system ' s default charset .
 * @ param in the stream to read .
 * @ return the stream ' s content as a { @ code String } .
 * @ throws NullPointerException if { @ code in } is { @ code null } .
 * @ throws IOException if the stream cannot be read . */
public static String read ( InputStream in ) throws IOException { } }

implementation: return read ( new InputStreamReader ( in , Charsets . DEFAULT ) ) ;


signature:
public class CharStreams { /** * Reads the whole content of the given { @ code InputStream } into a
 * { @ code String } using the specified charset .
 * @ param in the stream to read .
 * @ param charset the stream ' s charset .
 * @ return the stream ' s content as a { @ code String } .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if the stream cannot be read . */
public static String read ( InputStream in , Charset charset ) throws IOException { } }

implementation: return read ( new InputStreamReader ( in , charset ) ) ;


signature:
public class CharStreams { /** * Reads all the lines from the given source { @ code Reader } . Note that
 * the returned { @ code List } is immutable .
 * @ param in the stream to read .
 * @ return the stream ' s lines .
 * @ throws NullPointerException if { @ code in } is { @ code null } .
 * @ throws IOException if the stream cannot be read . */
public static List < String > readLines ( Reader in ) throws IOException { } }

implementation: BufferedReader reader = buffer ( in ) ; List < String > lines = new ArrayList < String > ( ) ; String line = reader . readLine ( ) ; while ( line != null ) { lines . add ( line ) ; line = reader . readLine ( ) ; } return Collections . unmodifiableList ( lines ) ;


signature:
public class CharStreams { /** * Reads all the lines from the given source { @ code InputStream } using
 * the system ' s default charset . Note that the returned { @ code List } is
 * immutable .
 * @ param in the stream to read .
 * @ return the stream ' s lines .
 * @ throws NullPointerException if { @ code in } is { @ code null } .
 * @ throws IOException if the stream cannot be read . */
public static List < String > readLines ( InputStream in ) throws IOException { } }

implementation: return readLines ( in , Charsets . DEFAULT ) ;


signature:
public class CharStreams { /** * Reads all the lines from the given source { @ code InputStream } using
 * the specified charset . Note that the returned { @ code List } is immutable .
 * @ param in the stream to read .
 * @ param charset the charset to use .
 * @ return the stream ' s lines .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if the stream cannot be read . */
public static List < String > readLines ( InputStream in , Charset charset ) throws IOException { } }

implementation: return readLines ( new InputStreamReader ( in , charset ) ) ;


signature:
public class KDFs { /** * Creates and returns a new immutable { @ code KDF } instance implementing
 * the PBKDF1 algorithm ( RFC 2898 ) .
 * @ param digest the digest algorithm to use .
 * @ param iterationCount the desired number of iterations .
 * @ param dkLen the desired length for derived keys , in bytes .
 * @ return the created { @ code KDF } instance .
 * @ throws NullPointerException if { @ code digest } is { @ code null } .
 * @ throws IllegalArgumentException if { @ code iterationCount } or
 * { @ code dkLen } is negative , or if { @ code dkLen } is greater than
 * the digest algorithm ' s output length , or if the digest algorithm
 * is unknown . */
public static KDF pbkdf1 ( Algorithm < Digest > digest , int iterationCount , int dkLen ) { } }

implementation: return new PBKDF1 ( digest , iterationCount , dkLen ) ;


signature:
public class KDFs { /** * Creates and returns a new immutable { @ code KDF } instance implementing
 * the PBKDF2 algorithm ( RFC 2898 ) .
 * @ param mac the MAC algorithm to use .
 * @ param iterationCount the desired number of iterations .
 * @ param dkLen the desired length for derived keys , in bytes .
 * @ return the created { @ code KDF } instance .
 * @ throws NullPointerException if { @ code mac } is { @ code null } .
 * @ throws IllegalArgumentException if { @ code iterationCount } or
 * { @ code dkLen } is negative , or if the MAC algorithm is unknown . */
public static KDF pbkdf2 ( Algorithm < MAC > mac , int iterationCount , int dkLen ) { } }

implementation: return new PBKDF2 ( mac , iterationCount , dkLen ) ;


signature:
public class KDFs { /** * Creates and returns a new immutable { @ code KDF } instance implementing
 * the HKDF algorithm ( RFC 5869 ) .
 * @ param mac the MAC algorithm to use .
 * @ param info optional context and application specific information ,
 * may be { @ code null } or empty .
 * @ param dkLen the desired length for derived keys , in bytes .
 * @ return the created { @ code KDF } instance .
 * @ throws NullPointerException if { @ code mac } is { @ code null } .
 * @ throws IllegalArgumentException if { @ code dkLen } is negative , or if
 * the MAC algorithm is unknown , or if { @ code dkLen } is greater
 * than 255 * MAC algorithm ' s output length . */
public static KDF hkdf ( Algorithm < MAC > mac , byte [ ] info , int dkLen ) { } }

implementation: return new HKDF ( mac , info , dkLen ) ;


signature:
public class KDFs { /** * Creates and returns a new immutable { @ code KDF } instance implementing
 * the SCrypt algorithm ( RFC 7914 ) .
 * @ param r the block size parameter .
 * @ param n the CPU / Memory cost parameter .
 * @ param p the parallelization parameter .
 * @ param dkLen the desired length for derived keys , in bytes .
 * @ return the created { @ code KDF } instance .
 * @ throws IllegalArgumentException if { @ code r , dkLen } or { @ code p } is
 * negative , or if { @ code n } is not greater than 1 or if it is not
 * a power of 2 or if it is not less than 2 ^ ( 128 * r / 8 ) , or if
 * { @ code p } is greater than ( ( 2 ^ 32 - 1 ) * 32 ) / ( 128 * r ) . */
public static KDF scrypt ( int r , int n , int p , int dkLen ) { } }

implementation: return new SCrypt ( r , n , p , dkLen ) ;


signature:
public class XFiles { /** * Copies the contents of { @ code src } to { @ code dst } . If { @ code dst }
 * doesn ' t exist , it will be created . If it already exists , it can be
 * either a directory or a regular file if { @ code src } is also a regular
 * file . Named after the Unix command of the same name .
 * @ param src the source { @ code File } .
 * @ param dst the target { @ code File } .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IllegalArgumentException if { @ code src } is a directory and
 * { @ code dst } is a regular file .
 * @ throws IOException if { @ code src } doesn ' t exist or if { @ code src } is
 * neither a regular file nor a directory or if an I / O error occurs
 * during the process .
 * @ throws SecurityException if a security manager exists and denies
 * read access to { @ code src } or write access to { @ code dst } . */
public static void cp ( File src , File dst ) throws IOException { } }

implementation: if ( ! src . exists ( ) ) { throw new FileNotFoundException ( src + " doesn't exist" ) ; } Parameters . checkCondition ( ( ! dst . exists ( ) || dst . isDirectory ( ) ) || ( src . isFile ( ) && dst . isFile ( ) ) ) ; if ( src . isDirectory ( ) ) { copyDirectory ( src , dst ) ; } else if ( src . isFile ( ) ) { copyFile ( src , dst ) ; } else { throw new IOException ( src + " is neither a directory nor a regular file" ) ; }


signature:
public class XFiles { /** * Copies the contents of the given input { @ code File } to the given
 * { @ code OutputStream } . Named after the Unix command of the same name .
 * @ param src the file to copy from .
 * @ param dst the stream to write to .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if { @ code src } does not exist , or if it is a
 * directory rather than a regular file , or if it can ' t be opened
 * for reading , or if an I / O error occurs during the process .
 * @ throws SecurityException if a security manager exists denies read
 * access to { @ code src } . */
public static void cp ( File src , OutputStream dst ) throws IOException { } }

implementation: InputStream in = newInputStream ( src ) ; try { ByteStreams . copy ( in , dst ) ; } finally { IO . close ( in ) ; }


signature:
public class XFiles { /** * Copies the contents of the given { @ code InputStream } to the given
 * output { @ code File } . Named after the Unix command of the same name .
 * @ param src the stream to read from .
 * @ param dst the file to write to .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IOException if { @ code dst } exists but is a directory rather
 * than a regular file , or if it does not exist but cannot be
 * created , or if an I / O error occurs during the process .
 * @ throws SecurityException if a security manager exists denies write
 * access to { @ code dst } . */
public static void cp ( InputStream src , File dst ) throws IOException { } }

implementation: OutputStream out = newOutputStream ( dst ) ; try { ByteStreams . copy ( src , out ) ; } finally { IO . close ( out ) ; }


signature:
public class XFiles { /** * Moves a file from one path to another . Named after the Unix command
 * of the same name .
 * @ param src the original file .
 * @ param dst the destination path .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IllegalArgumentException if { @ code src } is a directory and
 * { @ code dst } is a regular file .
 * @ throws IOException if { @ code src } can ' t be moved to { @ code dst } .
 * @ throws SecurityException if a security manager exists and denies
 * read / write access to { @ code src } / { @ code dst } . */
public static void mv ( File src , File dst ) throws IOException { } }

implementation: Parameters . checkNotNull ( dst ) ; if ( ! src . equals ( dst ) ) { cp ( src , dst ) ; try { rm ( src ) ; } catch ( IOException e ) { rm ( dst ) ; throw new IOException ( "Can't move " + src , e ) ; } }


signature:
public class XFiles { /** * Deletes the given { @ code File } s . Directories will be recursively
 * deleted . Named after the Unix command of the same name .
 * @ param files the { @ code File } s to delete .
 * @ throws NullPointerException if { @ code files } is { @ code null } or if
 * it contains a { @ code null } reference .
 * @ throws IOException if one of the specified { @ code File } s can ' t be
 * deleted .
 * @ throws SecurityException if a security manager exists and denies
 * read / write access to one of the specified files or its children . */
public static void rm ( File ... files ) throws IOException { } }

implementation: for ( File f : files ) { if ( f . exists ( ) ) { if ( f . isDirectory ( ) ) { rm ( f . listFiles ( ) ) ; } if ( ! f . delete ( ) ) { throw new IOException ( "Can't delete " + f ) ; } } }


signature:
public class XFiles { /** * Creates empty files at the specified paths or updates the last
 * modification time of the files at the specified paths . Named after
 * the Unix command of the same name .
 * @ param files the files to touch .
 * @ throws IOException if an I / O error occurs during the process .
 * @ throws SecurityException if a security manager exists and denies
 * read / write access to one of the specified files . */
public static void touch ( File ... files ) throws IOException { } }

implementation: long now = System . currentTimeMillis ( ) ; for ( File f : files ) { if ( ! f . createNewFile ( ) && ! f . setLastModified ( now ) ) { throw new IOException ( "Failed to touch " + f ) ; } }


signature:
public class XFiles { /** * Reads the first ( up to { @ code n } ) bytes of the given { @ code File } .
 * Named after the Unix command of the same name .
 * @ param f the file to read .
 * @ param n the maximum number of bytes to read .
 * @ return the first bytes of the given { @ code File } .
 * @ throws NullPointerException if { @ code f } is { @ code null } .
 * @ throws IllegalArgumentException if { @ code n } is negative .
 * @ throws IOException if { @ code f } does not exist , or if it is a
 * directory rather than a regular file , or if it can ' t be read .
 * @ throws SecurityException if a security manager exists and denies
 * read access to { @ code f } . */
public static byte [ ] head ( File f , int n ) throws IOException { } }

implementation: Parameters . checkCondition ( n >= 0 ) ; InputStream in = newInputStream ( f ) ; byte [ ] buf = new byte [ n ] ; try { return XArrays . copyOf ( buf , 0 , in . read ( buf ) ) ; } finally { IO . close ( in ) ; }


signature:
public class XFiles { /** * Reads the last ( up to { @ code n } ) bytes of the given { @ code File } .
 * Named after the Unix command of the same name .
 * @ param f the file to read .
 * @ param n the maximum number of bytes to read .
 * @ return the last bytes of the given { @ code File } .
 * @ throws NullPointerException if { @ code f } is { @ code null } .
 * @ throws IOException if { @ code f } does not exist , or if it is a
 * directory rather than a regular file , or if it can ' t be read .
 * @ throws SecurityException if a security manager exists and denies
 * read access to { @ code f } . */
public static byte [ ] tail ( File f , int n ) throws IOException { } }

implementation: Parameters . checkCondition ( n >= 0 ) ; RandomAccessFile file = new RandomAccessFile ( f , "r" ) ; file . seek ( file . length ( ) - n ) ; byte [ ] data = new byte [ n ] ; file . read ( data ) ; return data ;


signature:
public class XFiles { /** * Returns whether the given { @ code File } s have the same content . Two
 * regular files are considered equal if they contain the same bytes .
 * Two directories are considered equal if they both contain the same
 * items where an item is either a directory or a regular file ( items
 * must have the same name and content in both directories ) .
 * @ param f1 the first { @ code File } .
 * @ param f2 the second { @ code File } .
 * @ return whether the given { @ code File } s have the same content .
 * @ throws IOException if the content of the { @ code File } s can ' t be read . */
public static boolean equal ( File f1 , File f2 ) throws IOException { } }

implementation: if ( f1 == f2 ) { return true ; } if ( f1 == null || f2 == null || ! haveSameType ( f1 , f2 ) ) { return false ; } return f1 . equals ( f2 ) ? true : haveSameContent ( f1 , f2 ) ;


signature:
public class XFiles { /** * Returns the file name without its path or extension . This method is
 * named after the ' basename ' Unix command .
 * @ param f the file to get the base name .
 * @ return { @ code f } ' s extension - free name .
 * @ throws NullPointerException if { @ code f } is { @ code null } . */
public static String getBaseName ( File f ) { } }

implementation: String fileName = f . getName ( ) ; int index = fileName . lastIndexOf ( '.' ) ; return index == - 1 ? fileName : fileName . substring ( 0 , index ) ;


signature:
public class XFiles { /** * Returns an { @ code OutputStream } to write to the given { @ code File } .
 * @ param f the file to write to .
 * @ param options the write options .
 * @ return an { @ code OutputStream } to write to the given { @ code File } .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IllegalArgumentException if incompatible options are given .
 * @ throws FileNotFoundException if { @ code f } exists but is a directory
 * rather than a regular file , or if it does not exist but cannot
 * be created , or if it cannot be opened for any other reason .
 * @ throws IOException if the { @ link WriteOption # CREATE } option is given
 * and the specified file already exists .
 * @ throws SecurityException if a security manager exists and denies
 * write access to { @ code f } . */
public static BufferedOutputStream newOutputStream ( File f , WriteOption ... options ) throws IOException { } }

implementation: Set < WriteOption > opts = ImmutableSet . of ( options ) ; checkWriteOptions ( opts ) ; checkFileExistence ( f , opts ) ; return new BufferedOutputStream ( newOutputStream ( f , opts ) ) ;


signature:
public class XFiles { /** * Reads the content of the given { @ code File } .
 * @ param f the file to read .
 * @ return the file ' s content as a { @ code byte [ ] } .
 * @ throws NullPointerException if { @ code f } is { @ code null } .
 * @ throws IOException if { @ code f } does not exist , or if it is a
 * directory rather than a regular file , or if it can ' t be read .
 * @ throws SecurityException if a security manager exists and denies
 * read access to { @ code f } . */
public static byte [ ] read ( File f ) throws IOException { } }

implementation: InputStream in = newInputStream ( f ) ; try { return ByteStreams . read ( in ) ; } finally { IO . close ( in ) ; }


signature:
public class MediaType { /** * Parses a { @ code MediaType } from its { @ code String } representation .
 * @ param input the input { @ code String } to be parsed .
 * @ return the parsed { @ code MediaType } instance .
 * @ throws NullPointerException if { @ code input } is { @ code null } .
 * @ throws IllegalArgumentException if { @ code input } can ' t be parsed or
 * if a wildcard is used for the type , but not for the subtype . */
public static MediaType parse ( String input ) { } }

implementation: Parameters . checkNotNull ( input ) ; Matcher m = MEDIA_TYPE_PATTERN . matcher ( input ) ; Parameters . checkCondition ( m . matches ( ) ) ; String type = m . group ( 1 ) ; String subtype = m . group ( 2 ) ; String params = m . group ( 3 ) ; ParametersParser parser = new ParametersParser ( ) ; return create ( type , subtype , parser . parse ( params ) ) ;


signature:
public class MediaType { /** * Creates a new { @ code MediaType } with the given type and subtype .
 * @ param type the type .
 * @ param subtype the subtype .
 * @ return the created { @ code MediaType } instance .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IllegalArgumentException if type or subtype is invalid or if
 * a wildcard is used for the type , but not for the subtype . */
public static MediaType create ( String type , String subtype ) { } }

implementation: Map < String , String > params = Collections . emptyMap ( ) ; return create ( type , subtype , params ) ;


signature:
public class MediaType { /** * Returns the value of the charset parameter if it is specified , or
 * { @ code null } otherwise .
 * @ return the charset parameter ' s value if present , or { @ code null }
 * otherwise .
 * @ throws IllegalCharsetNameException if the charset is illegal .
 * @ throws UnsupportedCharsetException if the charset is not supported . */
public Charset charset ( ) { } }

implementation: String charset = parameters . get ( CHARSET ) ; return charset == null ? null : Charset . forName ( charset ) ;


signature:
public class MediaType { /** * Returns a new { @ code MediaType } instance similar to this one but with
 * the specified parameter set to the given value .
 * @ param attribute the attribute of the parameter to add .
 * @ param value the value of the parameter to add .
 * @ return the created { @ code MediaType } .
 * @ throws NullPointerException if one of the arguments is { @ code null } .
 * @ throws IllegalArgumentException if { @ code attribute } is invalid . */
public MediaType withParameter ( String attribute , String value ) { } }

implementation: Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( attribute , value ) ; return withParameters ( params ) ;


signature:
public class MediaType { /** * Returns a new { @ code MediaType } instance having the same type and
 * subtype as this one but whose parameters is the " union " of this
 * instances ' parameters with the given ones ( the given parameters have
 * precedence over this instance ' s parameters ) .
 * @ param parameters the parameters .
 * @ return the created { @ code MediaType } .
 * @ throws NullPointerException if { @ code parameters } is { @ code null } or
 * if it contains the { @ code null } key or a { @ code null } value .
 * @ throws IllegalArgumentException if { @ code parameters } contains an
 * invalid attribute . */
public MediaType withParameters ( Map < String , String > parameters ) { } }

implementation: Map < String , String > params = new LinkedHashMap < String , String > ( ) ; params . putAll ( this . parameters ) ; params . putAll ( normalizeParameters ( parameters ) ) ; return new MediaType ( type , subtype , params ) ;


signature:
public class MediaType { /** * Returns a new { @ code MediaType } instance similar to this one but
 * without the specified parameter .
 * @ param attribute the attribute of the parameter to remove .
 * @ return the created { @ code MediaType } .
 * @ throws NullPointerException if { @ code attribute } is { @ code null } . */
public MediaType withoutParameter ( String attribute ) { } }

implementation: Parameters . checkNotNull ( attribute ) ; Map < String , String > params = new LinkedHashMap < String , String > ( ) ; params . putAll ( parameters ) ; params . remove ( attribute ) ; return new MediaType ( type , subtype , params ) ;


signature:
public class MediaType { /** * Returns a new { @ code MediaType } instance with the same type and
 * subtype as this instance but without any parameters .
 * @ return the created { @ code MediaType } . */
public MediaType withoutParameters ( ) { } }

implementation: Map < String , String > params = Collections . emptyMap ( ) ; return new MediaType ( type , subtype , params ) ;


signature:
public class MediaType { /** * Returns whether this media type is within the specified media range .
 * Namely , it returns { @ code true } if the type of { @ code range } is the
 * wildcard or is equal to the type of this instance , and , if the
 * subtype of { @ code range } is the wildcard or is equal to the subtype
 * of this instance , and , if all the parameters present in { @ code range }
 * are also present in this instance .
 * @ param range the range to check this media type against .
 * @ return whether this media type is within the specified range .
 * @ throws NullPointerException if { @ code range } is { @ code null } . */
public boolean is ( MediaType range ) { } }

implementation: return ( range . type . equals ( WILDCARD ) || range . type . equals ( type ) ) && ( range . subtype . equals ( WILDCARD ) || range . subtype . equals ( subtype ) ) && parameters . entrySet ( ) . containsAll ( range . parameters . entrySet ( ) ) ;


signature:
public class Iterables { /** * Concatenates the given { @ code Iterable } s into a single one . Note that
 * the returned { @ code Iterable } is only a view , that is , any subsequent
 * update on any of the input { @ code Iterable } s will affect the returned
 * view . The input { @ code Iterable } s will not be polled until necessary .
 * The returned view ' s { @ code Iterator } supports { @ link Iterator # remove ( ) }
 * when the corresponding input { @ code Iterator } supports it .
 * @ param < T > the type of the returned { @ code Iterable } s ' elements .
 * @ param iterables the { @ code Iterable } s to concatenate .
 * @ return the concatenated { @ code Iterable } .
 * @ throws NullPointerException if { @ code iterables } is { @ code null } or
 * if it contains a { @ code null } reference . */
public static < T > Iterable < T > concat ( Iterable < ? extends Iterable < ? extends T > > iterables ) { } }

implementation: return new ConcatIterable < T > ( iterables ) ;