Introdução à programação orientada para aspectos em AspectJ. Diapositivos de seminário realizado no contexto da disciplina de Engenharia do Software II, DCTI, ISCTE-IUL.
This document discusses concurrency and concurrent programming in Java. It introduces the built-in concurrency primitives like wait(), notify(), synchronized, and volatile. It then discusses higher-level concurrency utilities and data structures introduced in JDK 5.0 like Executors, ExecutorService, ThreadPools, Future, Callable, ConcurrentHashMap, CopyOnWriteArrayList that provide safer and more usable concurrency constructs. It also briefly covers topics like Java Memory Model, memory barriers, and happens-before ordering.
The document contains source code for a client-server chat application written in Java. The client code establishes a socket connection to the server, reads user input and sends messages to the server. The server code initializes a server socket to listen for client connections, spawns a new thread for each client, reads incoming messages and sends responses. The code includes graphical user interface components for selecting the client or server role, composing and displaying messages.
The document contains source code for a client-server application written in Java. The client code establishes a socket connection to the server, allows sending and receiving messages, and closes the connection. The server code starts by binding to a port, accepts new connections from clients, and spawns a new thread to handle each client connection concurrently. It reads and writes data from the socket and closes the connection when the client disconnects. The code includes classes for the client, server, and thread handling each client connection.
The code examples show source code for a client and server application for a chat program. The client code defines functions for connecting to the server, sending and receiving messages. The server code defines functions for starting the server, accepting new connections from clients, and handling message receives and sends between connected clients. The code implements multi-threaded processing to concurrently handle multiple client connections to the server.
This document summarizes new features and enhancements in Java 7 including Project Coin, NIO.2, invokedynamic, Fork/Join framework, and concurrency utilities. It discusses how these features make threads, parallelism, and concurrency easier to work with in Java. Code examples are provided to illustrate the use of ForkJoinPool, Callable, and try-with-resources statements.
Carol McDonald gave a presentation on Java concurrency utilities introduced in J2SE 5.0. She discussed motivation for improved concurrency tools, common concurrency issues, and key utilities like Executor framework, locks, synchronizers, and concurrent collections. The utilities make concurrent programming easier and improve performance of multithreaded Java applications.
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
The document discusses new features in Java SE 7 including the Fork/Join framework for parallel programming, language evolutions through Project Coin such as try-with-resources statements, and diamond syntax for generic types which simplifies generic class instance creation. It also covers varargs syntax simplification and restrictions on using diamond syntax with anonymous inner classes.
The document describes a network programming report on a Java chat application. It includes the code for a Server class that implements a threaded server to handle multiple client connections simultaneously. The server opens a port to listen for clients and spins up a new thread for each accepted connection. It then reads and writes data between the server and client over buffered input/output streams. The report notes issues with messages from one client not being visible to others and connection errors that can occur between the client and server.
This document discusses concurrency and concurrent programming in Java. It introduces the built-in concurrency primitives like wait(), notify(), synchronized, and volatile. It then discusses higher-level concurrency utilities and data structures introduced in JDK 5.0 like Executors, ExecutorService, ThreadPools, Future, Callable, ConcurrentHashMap, CopyOnWriteArrayList that provide safer and more usable concurrency constructs. It also briefly covers topics like Java Memory Model, memory barriers, and happens-before ordering.
The document contains source code for a client-server chat application written in Java. The client code establishes a socket connection to the server, reads user input and sends messages to the server. The server code initializes a server socket to listen for client connections, spawns a new thread for each client, reads incoming messages and sends responses. The code includes graphical user interface components for selecting the client or server role, composing and displaying messages.
The document contains source code for a client-server application written in Java. The client code establishes a socket connection to the server, allows sending and receiving messages, and closes the connection. The server code starts by binding to a port, accepts new connections from clients, and spawns a new thread to handle each client connection concurrently. It reads and writes data from the socket and closes the connection when the client disconnects. The code includes classes for the client, server, and thread handling each client connection.
The code examples show source code for a client and server application for a chat program. The client code defines functions for connecting to the server, sending and receiving messages. The server code defines functions for starting the server, accepting new connections from clients, and handling message receives and sends between connected clients. The code implements multi-threaded processing to concurrently handle multiple client connections to the server.
This document summarizes new features and enhancements in Java 7 including Project Coin, NIO.2, invokedynamic, Fork/Join framework, and concurrency utilities. It discusses how these features make threads, parallelism, and concurrency easier to work with in Java. Code examples are provided to illustrate the use of ForkJoinPool, Callable, and try-with-resources statements.
Carol McDonald gave a presentation on Java concurrency utilities introduced in J2SE 5.0. She discussed motivation for improved concurrency tools, common concurrency issues, and key utilities like Executor framework, locks, synchronizers, and concurrent collections. The utilities make concurrent programming easier and improve performance of multithreaded Java applications.
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
The document discusses new features in Java SE 7 including the Fork/Join framework for parallel programming, language evolutions through Project Coin such as try-with-resources statements, and diamond syntax for generic types which simplifies generic class instance creation. It also covers varargs syntax simplification and restrictions on using diamond syntax with anonymous inner classes.
The document describes a network programming report on a Java chat application. It includes the code for a Server class that implements a threaded server to handle multiple client connections simultaneously. The server opens a port to listen for clients and spins up a new thread for each accepted connection. It then reads and writes data between the server and client over buffered input/output streams. The report notes issues with messages from one client not being visible to others and connection errors that can occur between the client and server.
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
Distributed systems have several advantages including resource sharing, increased computation speed through parallel processing, and reliability through independent memory in each processor. There are different types of distributed operating systems based on how data, computations, or processes are transferred between sites. Mutual exclusion in distributed systems aims to ensure that only one process executes in the critical section at a time, while still allowing every request to enter and exit to eventually be granted. This can be achieved through centralized, distributed, or token passing approaches.
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
Julien Ponge
This talk introduces part of the Java SE 7 novelties. The fork/join framework aims at making parallel programming simpler, while Project Coin brings a set of subtle yet useful changes to the Java programming language.
http://soft-shake.ch/2011/conference/sessions/java/2011/09/06/java7.html
REX about JavaFX8 used in SlideshowFX. This presentation covers concept from JavaFX as well as technologies like OSGi, Vert.x, LeapMotion, nashorn and friends in order to make them communicate inside one application developed in JavaFX.
This presentation was made at the ElsassJUG
JavaFX 8 est disponible depuis mars 2014 et apporte son lot de nouveautés. Gradle est en version 2 depuis juillet 2014. Deux technologies plus que prometteuses: JavaFX donne un coup de jeune au développement d’applications desktop en Java en apportant un navigateur web intégré, le support des WebSockets, de la 3D, et bien d’autres. Gradle est l’outil de d’automatisation de build à la mode, apportant de superbes possibilités par rapport rapport à maven, outil vieillissant, grâce à l’engouement de la communauté vis à vis de cet outil mais aussi par le fait de la technologie utilisée en son sein: groovy. Venez découvrir comment il est possible de réaliser rapidement une application à la mode en JavaFX avec un outil à la mode également. Bref venez à une session trendy.
This document contains code snippets related to Spring Security configuration and authentication. It defines classes and methods for configuring security, processing login requests, loading user details, and authenticating users. Key aspects include configuring security filters and authorization rules, processing username/password authentication, validating login credentials against encoded passwords, and loading pre-authenticated users based on access tokens.
Understanding Source Code Differences by Separating Refactoring EffectsShinpei Hayashi
The document discusses separating refactoring effects from source code differences by describing refactoring changes that were made between versions of code. It provides an example of refactoring changes made between two versions of code, including renaming a class and parameters, deleting a for-loop, commenting out code, and renaming a method. The example highlights how refactoring can introduce differences that are not actual behavior changes.
The document discusses Simple API for XML (SAX), an event-based model for parsing XML documents. SAX involves defining handler methods that are called when XML parsing events occur, like start elements or character data. This allows applications to process XML documents as they are parsed without loading the entire document into memory. The example shows a SAX parser that outputs a tree structure of an XML document by overriding handler methods.
The document discusses Java SE 7 features including Project Coin, NIO.2, invokedynamic, and Fork/Join framework. It provides examples of using try-with-resources to automatically close resources without finally blocks, and using the Fork/Join framework to easily parallelize tasks by splitting work, forking subtasks, and joining results.
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
This document provides an overview of software testing concepts and the JUnit testing framework. It discusses the importance of testing, different types of testing, unit testing with JUnit, best practices for writing tests, integrating tests into builds with Ant and Maven, and logging. Examples of JUnit tests are also provided. The key points covered are:
- Why testing is important to find bugs, prevent regressions, and allow for refactoring
- Unit testing, functional testing, and other types of testing
- How to write automated unit tests with JUnit
- Best practices like testing edge cases, achieving good code coverage
- Integrating tests into builds with Ant and Maven
- Using logging frameworks like Log
The document discusses new features in Java SE 7 including Project Coin, NIO.2, invokedynamic, and try-with-resources. It also covers concurrency topics such as fork/join, executors, and synchronization patterns. Examples are provided for using fork/join tasks to sum arrays in parallel and the try-with-resources statement to ensure stream resources are closed automatically.
Conf soat tests_unitaires_Mockito_jUnit_170113SOAT
Vous subissez les régressions à chaque livraison ? Vous ne voyez pas l’intérêt des tests unitaires car ils ne servent qu’à tester des additions ? Si c’est le cas, suivez David dans la quête du Test Driven Development. Nous rencontrerons pléthore d'ennemies contre lesquels nous aurons à combattre : bugs, complexité, code statique, couplage fort. Ils essaieront de nous barrer la route, mais heureusement, nous pourrons compter sur nos alliés jUnit, Mockito, refactoring et injection/dépendance
This document describes the implementation of a simple REST server in Qt using reflection. It discusses how the Qt meta-object compiler (moc) is used, the abstract and concrete server classes, building the route tree using reflection, handling new connections in worker threads, calling methods based on the request, and using reflection for testing. The abstract server class inherits from QTcpServer and uses slots decorated with tags to implement routes. Worker threads handle individual connections and parse requests to call the appropriate method. Reflection is leveraged throughout to build routes and dispatch requests without explicit registration or mapping.
The document contains code for an image processing program that:
1) Loads a series of images from a file into memory and analyzes frame differences to determine scene changes.
2) Applies frame transformations to adjust for motion between images.
3) Generates a reduced set of frames to display by selecting key frames around detected scene changes.
The program analyzes histograms, motion vectors, and color differences between frames to evaluate scene changes and filter out unnecessary frames.
The Ring programming language version 1.3 book - Part 17 of 88Mahmoud Samir Fayed
This document discusses various file handling functions in Ring including:
- Tempfile() which creates a temporary file that is deleted when closed
- Tempname() which generates a unique temporary file name
- Fseek(), Ftell(), Rewind() which set/get the file position indicator
- Fgetpos(), Fsetpos() which get/set the file position handle
- Clearerr(), Feof(), Ferror() which clear errors or check end-of-file or errors
- Perror() which prints error messages
- Functions for reading/writing characters and strings to files
- Ungetc() which pushes a character back into the stream
- Fread(), Fwrite() which read/write
This document discusses techniques for detecting and preventing SQL injection using the Percona Toolkit and Noinject!. It begins by introducing SQL injection and how attackers can modify SQL queries without changing server code. It then discusses using query fingerprints to detect new queries that may indicate injection attempts. The Percona Toolkit tools pt-query-digest and pt-fingerprint are used to generate and store fingerprints in a whitelist. Pt-query-digest can detect new fingerprints that have not been reviewed. The Noinject! proxy script uses fingerprints to inspect queries in real-time and block any that do not match whitelisted patterns. The document concludes by discussing limitations and ways to improve the fingerprinting approach.
This document describes how to configure Spring Security for authentication and authorization in a web application. It defines a WebSecurityConfig class that configures HTTP security with roles like OWNER and MANAGER for access control. It also defines a UserDetailsManager service for loading users and a User entity class implementing UserDetails. Tests are shown for security configuration, login, access control and more using Spring Security's test utilities.
The document discusses common concurrency problems in Java like shared mutable state, visibility issues, inconsistent synchronization, and unsafe publication and provides examples of how to properly implement threading concepts like locking, waiting and notifying with synchronization, volatile variables, atomic classes and safe initialization techniques to avoid concurrency bugs. It also cautions against unsafe practices like synchronizing on the wrong objects or misusing threading methods that can lead to deadlocks, race conditions and other concurrency problems.
This document summarizes key features introduced in Java SE 5.0 (Tiger) including generics, autoboxing/unboxing, enhanced for loops, type-safe enums, varargs, static imports, and annotations. It also discusses performance enhancements in the virtual machine as well as new concurrency utilities like Executors and ScheduledExecutorService that make multi-threaded programming easier and more robust.
1) The document discusses the process of adding Ethernet functionality to an Android device using the MangoBoard. It describes initializing the Ethernet service during boot up and registering it with the ConnectivityService.
2) When an Ethernet connection is detected, the EthernetMonitor thread notifies the EthernetStateTracker which triggers DHCP configuration of the interface.
3) The DHCPHandler is then sent a message to start the DHCP process and obtain an IP address for the connected Ethernet interface.
12. Paradigmas da programação; Programação orientada por objectos; Pacotes – ...Manuel Menezes de Sequeira
Fundamentos da Programação 12:
• Paradigmas da programação
• Programação orientada por objectos
• Modularização em pacotes
Apresentação 12 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
9. Operação toString(); Classes, instâncias e objectos; Scanner – Fundamentos...Manuel Menezes de Sequeira
Este documento discute três tópicos principais: 1) A operação toString que é usada para converter objetos em strings; 2) A diferença entre classes, instâncias e objetos; 3) Como realizar leituras usando a classe Scanner.
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
Distributed systems have several advantages including resource sharing, increased computation speed through parallel processing, and reliability through independent memory in each processor. There are different types of distributed operating systems based on how data, computations, or processes are transferred between sites. Mutual exclusion in distributed systems aims to ensure that only one process executes in the critical section at a time, while still allowing every request to enter and exit to eventually be granted. This can be achieved through centralized, distributed, or token passing approaches.
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
Julien Ponge
This talk introduces part of the Java SE 7 novelties. The fork/join framework aims at making parallel programming simpler, while Project Coin brings a set of subtle yet useful changes to the Java programming language.
http://soft-shake.ch/2011/conference/sessions/java/2011/09/06/java7.html
REX about JavaFX8 used in SlideshowFX. This presentation covers concept from JavaFX as well as technologies like OSGi, Vert.x, LeapMotion, nashorn and friends in order to make them communicate inside one application developed in JavaFX.
This presentation was made at the ElsassJUG
JavaFX 8 est disponible depuis mars 2014 et apporte son lot de nouveautés. Gradle est en version 2 depuis juillet 2014. Deux technologies plus que prometteuses: JavaFX donne un coup de jeune au développement d’applications desktop en Java en apportant un navigateur web intégré, le support des WebSockets, de la 3D, et bien d’autres. Gradle est l’outil de d’automatisation de build à la mode, apportant de superbes possibilités par rapport rapport à maven, outil vieillissant, grâce à l’engouement de la communauté vis à vis de cet outil mais aussi par le fait de la technologie utilisée en son sein: groovy. Venez découvrir comment il est possible de réaliser rapidement une application à la mode en JavaFX avec un outil à la mode également. Bref venez à une session trendy.
This document contains code snippets related to Spring Security configuration and authentication. It defines classes and methods for configuring security, processing login requests, loading user details, and authenticating users. Key aspects include configuring security filters and authorization rules, processing username/password authentication, validating login credentials against encoded passwords, and loading pre-authenticated users based on access tokens.
Understanding Source Code Differences by Separating Refactoring EffectsShinpei Hayashi
The document discusses separating refactoring effects from source code differences by describing refactoring changes that were made between versions of code. It provides an example of refactoring changes made between two versions of code, including renaming a class and parameters, deleting a for-loop, commenting out code, and renaming a method. The example highlights how refactoring can introduce differences that are not actual behavior changes.
The document discusses Simple API for XML (SAX), an event-based model for parsing XML documents. SAX involves defining handler methods that are called when XML parsing events occur, like start elements or character data. This allows applications to process XML documents as they are parsed without loading the entire document into memory. The example shows a SAX parser that outputs a tree structure of an XML document by overriding handler methods.
The document discusses Java SE 7 features including Project Coin, NIO.2, invokedynamic, and Fork/Join framework. It provides examples of using try-with-resources to automatically close resources without finally blocks, and using the Fork/Join framework to easily parallelize tasks by splitting work, forking subtasks, and joining results.
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
This document provides an overview of software testing concepts and the JUnit testing framework. It discusses the importance of testing, different types of testing, unit testing with JUnit, best practices for writing tests, integrating tests into builds with Ant and Maven, and logging. Examples of JUnit tests are also provided. The key points covered are:
- Why testing is important to find bugs, prevent regressions, and allow for refactoring
- Unit testing, functional testing, and other types of testing
- How to write automated unit tests with JUnit
- Best practices like testing edge cases, achieving good code coverage
- Integrating tests into builds with Ant and Maven
- Using logging frameworks like Log
The document discusses new features in Java SE 7 including Project Coin, NIO.2, invokedynamic, and try-with-resources. It also covers concurrency topics such as fork/join, executors, and synchronization patterns. Examples are provided for using fork/join tasks to sum arrays in parallel and the try-with-resources statement to ensure stream resources are closed automatically.
Conf soat tests_unitaires_Mockito_jUnit_170113SOAT
Vous subissez les régressions à chaque livraison ? Vous ne voyez pas l’intérêt des tests unitaires car ils ne servent qu’à tester des additions ? Si c’est le cas, suivez David dans la quête du Test Driven Development. Nous rencontrerons pléthore d'ennemies contre lesquels nous aurons à combattre : bugs, complexité, code statique, couplage fort. Ils essaieront de nous barrer la route, mais heureusement, nous pourrons compter sur nos alliés jUnit, Mockito, refactoring et injection/dépendance
This document describes the implementation of a simple REST server in Qt using reflection. It discusses how the Qt meta-object compiler (moc) is used, the abstract and concrete server classes, building the route tree using reflection, handling new connections in worker threads, calling methods based on the request, and using reflection for testing. The abstract server class inherits from QTcpServer and uses slots decorated with tags to implement routes. Worker threads handle individual connections and parse requests to call the appropriate method. Reflection is leveraged throughout to build routes and dispatch requests without explicit registration or mapping.
The document contains code for an image processing program that:
1) Loads a series of images from a file into memory and analyzes frame differences to determine scene changes.
2) Applies frame transformations to adjust for motion between images.
3) Generates a reduced set of frames to display by selecting key frames around detected scene changes.
The program analyzes histograms, motion vectors, and color differences between frames to evaluate scene changes and filter out unnecessary frames.
The Ring programming language version 1.3 book - Part 17 of 88Mahmoud Samir Fayed
This document discusses various file handling functions in Ring including:
- Tempfile() which creates a temporary file that is deleted when closed
- Tempname() which generates a unique temporary file name
- Fseek(), Ftell(), Rewind() which set/get the file position indicator
- Fgetpos(), Fsetpos() which get/set the file position handle
- Clearerr(), Feof(), Ferror() which clear errors or check end-of-file or errors
- Perror() which prints error messages
- Functions for reading/writing characters and strings to files
- Ungetc() which pushes a character back into the stream
- Fread(), Fwrite() which read/write
This document discusses techniques for detecting and preventing SQL injection using the Percona Toolkit and Noinject!. It begins by introducing SQL injection and how attackers can modify SQL queries without changing server code. It then discusses using query fingerprints to detect new queries that may indicate injection attempts. The Percona Toolkit tools pt-query-digest and pt-fingerprint are used to generate and store fingerprints in a whitelist. Pt-query-digest can detect new fingerprints that have not been reviewed. The Noinject! proxy script uses fingerprints to inspect queries in real-time and block any that do not match whitelisted patterns. The document concludes by discussing limitations and ways to improve the fingerprinting approach.
This document describes how to configure Spring Security for authentication and authorization in a web application. It defines a WebSecurityConfig class that configures HTTP security with roles like OWNER and MANAGER for access control. It also defines a UserDetailsManager service for loading users and a User entity class implementing UserDetails. Tests are shown for security configuration, login, access control and more using Spring Security's test utilities.
The document discusses common concurrency problems in Java like shared mutable state, visibility issues, inconsistent synchronization, and unsafe publication and provides examples of how to properly implement threading concepts like locking, waiting and notifying with synchronization, volatile variables, atomic classes and safe initialization techniques to avoid concurrency bugs. It also cautions against unsafe practices like synchronizing on the wrong objects or misusing threading methods that can lead to deadlocks, race conditions and other concurrency problems.
This document summarizes key features introduced in Java SE 5.0 (Tiger) including generics, autoboxing/unboxing, enhanced for loops, type-safe enums, varargs, static imports, and annotations. It also discusses performance enhancements in the virtual machine as well as new concurrency utilities like Executors and ScheduledExecutorService that make multi-threaded programming easier and more robust.
1) The document discusses the process of adding Ethernet functionality to an Android device using the MangoBoard. It describes initializing the Ethernet service during boot up and registering it with the ConnectivityService.
2) When an Ethernet connection is detected, the EthernetMonitor thread notifies the EthernetStateTracker which triggers DHCP configuration of the interface.
3) The DHCPHandler is then sent a message to start the DHCP process and obtain an IP address for the connected Ethernet interface.
12. Paradigmas da programação; Programação orientada por objectos; Pacotes – ...Manuel Menezes de Sequeira
Fundamentos da Programação 12:
• Paradigmas da programação
• Programação orientada por objectos
• Modularização em pacotes
Apresentação 12 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
9. Operação toString(); Classes, instâncias e objectos; Scanner – Fundamentos...Manuel Menezes de Sequeira
Este documento discute três tópicos principais: 1) A operação toString que é usada para converter objetos em strings; 2) A diferença entre classes, instâncias e objetos; 3) Como realizar leituras usando a classe Scanner.
3. Funções/repórteres e listas em Snap!; Utilização de variáveis – Fundamento...Manuel Menezes de Sequeira
Fundamentos da Programação 3:
• Funções/repórteres e listas em Snap!
• Utilizações típicas de variáveis
Apresentação 3 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
O documento introduz conceitos do UML como ligações como instâncias de associações, multiplicidade de classes como solitões e classes-pacote, e diagramas de sequência.
7. Arrays multidimensionais; Estratégias de resolução de problemas – Fundamen...Manuel Menezes de Sequeira
Fundamentos da Programação 7:
• Arrays multidimensionais
• Estratégias de resolução de problemas
Apresentação 7 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
Fundamentos da Programação 8:
• Classes e instâncias
• Cadeias de caracteres
Apresentação 8 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
Aula teórica 1 da unidade (disciplina) de Programação Orientada por Objectos dos cursos de LIGE, LEI e LETI no ISCTE-IUL no 2.º semestre do ano lectivo de 2009/2010.
Aula teórica 6 da unidade (disciplina) de Programação Orientada por Objectivos para os cursos de LIGE, LEI e LETI no ISCTE-IUL no 2.º semestre do ano lectivo de 2009/2010.
Este documento apresenta os principais conceitos da linguagem de programação Java, incluindo variáveis, instruções de seleção e iteração, funções, métodos de classe e instância, escrita no ecrã e o método principal main. O documento explica como Java lida com comentários e fornece exemplos de código para ilustrar estes conceitos.
13. Polimorfismo de subtipos; Análise, desenho e implementação – Fundamentos ...Manuel Menezes de Sequeira
Fundamentos da Programação 13:
• Polimorfismo de subtipos
• Análise, desenho e implementação
Apresentação 13 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
O documento discute interfaces, listas e listas ligadas e iteradores em programação orientada a objetos. Aborda como interfaces definem comportamentos que classes podem implementar e como classes genéricas como listas ligadas permitem armazenar diferentes tipos de elementos de forma polimórfica. Explica operações básicas em listas ligadas como inserção e remoção e como iteradores permitem percorrer listas de forma paralela.
11. Enumerações; Instrução switch; Limitações dos inteiros – Fundamentos de P...Manuel Menezes de Sequeira
1. O documento discute enumerações, a instrução switch e os limites dos tipos inteiros em Java.
2. Enumerações permitem definir tipos de dados com valores fixos. A instrução switch permite selecionar fluxos de execução com base em valores enumerados.
3. Os tipos inteiros em Java têm gamas limitadas, com valores mínimos e máximos definidos. A classe BigInteger permite trabalhar com números inteiros de precisão arbitrária.
5. Atribuições especiais; Arrays; Tipos de ciclos; Classes-pacote – Fundament...Manuel Menezes de Sequeira
Fundamentos da Programação 5:
• Atribuições especiais
• Arrays em Java
• Tipos de ciclos (while e do-while, for e foreach)
• Classes-pacote
Apresentação 5 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
2. Programação e resolução de problemas; Algoritmos; Snap! – Fundamentos de P...Manuel Menezes de Sequeira
Fundamentos da Programação 2:
• Programação como arte de resolução de problemas
• Algoritmos
• Descrição de algoritmos em… Snap!
Apresentação 2 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
10. Encapsulação; Cópia de instâncias; Igualdade de instâncias – Fundamentos ...Manuel Menezes de Sequeira
O documento discute os conceitos de encapsulamento, cópia e igualdade de instâncias em programação orientada a objetos. Apresenta como encapsulamento aplica o conceito de ocultação de informação para separar a interface de uma classe de sua implementação. Também explica a necessidade de construtores de cópia e métodos de igualdade para comparar e copiar instâncias corretamente.
Aula teórica 2 da unidade (disciplina) de Programação Orientada por Objectivos para os cursos de LIGE, LEI e LETI no ISCTE-IUL no 2.º semestre do ano lectivo de 2009/2010.
1. Computador; Línguas naturais; Linguagens de Programação; Algoritmo e progr...Manuel Menezes de Sequeira
Fundamentos da Programação 1:
• Computador como máquina programável
• Conceitos de línguas naturais, linguagens de programação de baixo e de alto nível, e linguagens máquina
• Noções de algoritmo e de programa
Apresentação 1 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
O documento discute erros e casos excepcionais em Java, incluindo conceitos, representação, criação, detecção e tratamento. Aborda exceções Java, asserções Java e boas práticas, incluindo segurança.
14. Interfaces; Listas e cadeias ligadas; Iteradores – Fundamentos de Program...Manuel Menezes de Sequeira
Fundamentos da Programação 14:
• Interfaces
• Listas e cadeias ligadas
• Iteradores
Apresentação 14 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
In this chapter, we will discuss session tracking in JSP. HTTP is a "stateless" protocol which means each time a client retrieves a Webpage, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Maintaining Session Between Web Client And Server
Let us now discuss a few options to maintain the session between the Web Client and the Web Server −
Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
This document discusses refactoring code to improve its design without changing external behavior. It notes that refactoring involves making small, incremental changes rather than large "big bang" refactorings. Code smells that may indicate a need for refactoring include duplication, long methods, complex conditional logic, speculative code, and overuse of comments. Techniques discussed include extracting methods, removing duplication, using meaningful names, removing temporary variables, and applying polymorphism. The document emphasizes that refactoring is an investment that makes future changes easier and helps avoid bugs, and encourages learning from other programming communities.
The document discusses servlet session management. It covers servlet filters which can intercept and modify requests and responses. It also discusses the servlet context and configuration parameters, as well as the session object and APIs. Session attributes allow data to be stored and shared across requests from the same client, while context attributes are shared across the entire application. Session tracking allows associating requests from the same client, typically using cookies or URL rewriting to pass the session identifier.
BigQuery JavaScript User-Defined Functions by THOMAS PARK and FELIPE HOFFA at...Big Data Spain
Performing ETL on big data can be slow, expensive and painful - but it doesn't have to be! In this session, we'll take an in-depth look at several real-world examples of computations that don't fit well with the SQL language model and how to solve them with user-defined functions in Google BigQuery.
Session presented at Big Data Spain 2014 Conference
18th Nov 2014
Kinépolis Madrid
http://www.bigdataspain.org
Event promoted by: http://www.paradigmatecnologico.com
Abstract: http://www.bigdataspain.org/2014/conference/hands-on-with-bigquery-javascript-user-defined-functions
This document summarizes Paco de la Cruz's presentation on Azure Durable Functions. The presentation covered the evolution of application platforms from on-premises to serverless. It then discussed Azure Functions and some challenges it faces with stateful orchestrations. Durable Functions were introduced as an extension of Azure Functions that uses a Durable Task Framework to implement stateful workflows in a serverless manner. Key patterns demonstrated include function chaining, fan-out/fan-in, and using an orchestration client to start and monitor orchestrations. Code samples and demos were provided to illustrate approval workflows using Durable Functions.
The document discusses using annotations in Java, providing examples of annotations for servlets, EJBs, web services, CDI, and using frameworks like JUnit, Spring, Javassist, and ASM. It presents code samples to define servlets, session beans, RESTful and SOAP web services, and component injection using annotations instead of XML configurations. The document also demonstrates how to programmatically read annotation values and metadata using reflection, Javassist, and ASM.
Reactive Data System is a framework which is highly responsive to change in state of data. This can be used in developing
data-intensive enterprise application. Consider an example of e-retail whenever a consumer place an order it need to be notified to multiple department namely shipping, warehouse, finance, etc. Normally this is achieved with the help of
call stack mechanism, developer has to call each action or a function explicitly evertime order is placed or a payment is done, as this is executed synchronously one after another leading to high coupling and directly effect the response time leading to bad user experience.
Using RDS, developer can separate such action which can be carried out independently making loose coupling among components
of user app. It works on principle of Event driven architecture. One may think why to worry about RDS when same thing can
be achieved with the help of triggers. But triggers in sql has many limitation such as max number of triggers on a table, no user defined function can be called when though triggers, no multiple database support. All this limitations are overcomes through our RDS.
RDS provide GUI and API for Developer to register events and actions. There can be N action on 1 events. Along with data driven events we are supporting time driven events.
The document discusses different state management techniques in ASP.NET. It describes client-side techniques like hidden fields, view state, cookies, query strings, and control state. It also describes server-side techniques like session state and application state. Session state stores and retrieves data for each user session while application state stores data accessible to all users. Examples are provided for hidden fields, view state, cookies, query strings, session state, and application state.
Threads, Queues, and More: Async Programming in iOSTechWell
To keep your iOS app running butter-smooth at 60 frames per second, Apple recommends doing as many tasks as possible asynchronously or “off the main thread.” Joe Keeley introduces you to some basic concepts of asynchronous programming in iOS. He discusses what threads and queues are, how they are related, and the special significance of the main queue to iOS. Look at what options are available in the iOS SDK to work asynchronously, including NSOperationQueues and Grand Central Dispatch. Take an in depth look at how to implement some common use cases for those options in Swift. Joe pays special attention to networking, one of the most common asynchronous use cases. Spend some time discussing common asynchronous programming pitfalls—and how to avoid them. Leave this session ready to try out asynchronous programming in your iOS app.
Session tracking allows servlets to maintain state about each user across multiple requests. It works by assigning each user a unique ID (usually stored in a cookie) to identify them on subsequent requests, since HTTP is stateless. The main session tracking techniques are cookies, hidden form fields, URL rewriting, and HTTP sessions. HTTP sessions provide the most commonly used and flexible approach to session tracking in servlets.
The document discusses Google App Engine task queues and cron jobs. It provides examples of creating and using default and named push queues, as well as pull queues. It explains how to add tasks, lease tasks from pull queues, and delete tasks. It also covers using task queues within transactions. Additionally, it demonstrates configuring and using cron jobs to schedule recurring tasks.
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
Presentation about how to build flexible (using fragments), smooth (using async tasks and intent services) and "data up to date" (using loaders) Android applications.
Java Svet - Communication Between Android App ComponentsPSTechSerbia
Presentation about how to build flexible (using fragments), smooth (using async tasks and intent services) and "data up to date" (using loaders) Android applications.
Unit Testing Basics discusses the definition, types, benefits, and best practices of unit testing. The key points are:
- Unit tests verify small elements of code like classes or methods and have characteristics like being fast, isolated, repeatable, and self-checking.
- Different types of tests include unit tests, component tests, system tests, and functional tests which test at different scopes and have varying execution times.
- Well-designed unit tests provide benefits like documentation, error detection, and code improvements. Tests should be written before code using techniques like test-driven development.
- Frameworks like EasyMock can be used to create test doubles and mock objects to isolate the system under test and verify
- Practical exercises on the use of the threads with TCP
- References
YouTube link :
https://www.youtube.com/playlist?list=PLtDIUAtyP4lhV7CsYfLuIx26UeG4J-ujZ
GitHub :
https://github.com/Ghadeerof
The document discusses techniques for improving iOS application build performance and reducing executable size in Xamarin applications. It recommends measuring build times, optimizing for the iOS simulator by avoiding rebuilds and file copying, and optimizing for iOS devices by partially linking assemblies, using the LinkerSafe attribute, and leveraging SmartLink and automatic bindings optimizations. Building configurations and deployment tradeoffs are also covered.
Similar to Introdução à programação orientada para aspectos (20)
6. Caracteres; Tipos char e int; Tipos de valor e de referência – Fundamentos...Manuel Menezes de Sequeira
Fundamentos da Programação 6:
• Manipulação de caracteres
• Relação entre os tipos char e int
• Tipos de valor vs. tipos de referência
Apresentação 6 da unidade curricular de Fundamentos de Programação da Universidade Europeia. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI do ISCTE-IUL, incluindo Luís Nunes, Ricardo Ribeiro, André Santos e o próprio Manuel Menezes de Sequeira.
Apresentação da semana 10 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
Apresentação da semana 9 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
Apresentação da semana 8 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
1) As matrizes podem ter mais de uma dimensão, representando dados multidimensionais. Isto permite armazenar dados em estruturas aninhadas como matrizes de matrizes.
2) Para resolver problemas é importante decompor o problema em etapas menores, explorar possíveis soluções e testá-las, e refletir sobre a solução encontrada.
3) George Pólya forneceu estratégias úteis para a resolução de problemas como compreender o problema, decompor em subproblemas, explorar analogias e verificar a solução.
Semana 5: Caracteres, tipos char e int, tipos de valor vs. tipos de referênciaManuel Menezes de Sequeira
O documento discute a manipulação de caracteres em Java, incluindo a relação entre os tipos char e int e a diferença entre tipos de valor e tipos de referência. É apresentado como cada caractere tem um código único e como caracteres podem ser convertidos entre char e int. A distinção entre passagem por valor e passagem por referência é explicada.
O documento discute operadores de atribuição especiais em Java, matrizes, tipos de ciclos incluindo o ciclo for, e classes pacote. Apresenta exemplos de declaração e uso de matrizes, as partes de um ciclo, a diferença entre ciclos while e for, e como criar e usar uma classe pacote para organizar métodos relacionados a arrays.
Apresentação da semana 3 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
Apresentação da semana 2 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
Semana 1: Programação como arte de resolver problemas, algoritmos e problema...Manuel Menezes de Sequeira
Apresentação da semana 1 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
Semana 0: Computadores, linguagens e linguagens de programação, Noções de al...Manuel Menezes de Sequeira
Apresentação da semana 0 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
Apresentação da semana 11 da unidade curricular de Introdução à Programação do DCTI do ISCTE-IUL. Alterações de Manuel Menezes de Sequeira sobre versão original por vários autores do DCTI, incluindo Luís Nunes e André Santos.
Desenho de interfaces com o utilizador. Unidade de Engenharia do Software I para o curso de METI no ISCTE-IUL no 2.º semestre do ano lectivo de 2009/2010.
Este documento discute o desenho arquitectónico de software, apresentando três estilos arquitectónicos para organização, decomposição e controlo de sistemas. Também discute decisões no desenho arquitectónico e arquitecturas de referência.
A Visual Guide to 1 Samuel | A Tale of Two HeartsSteve Thomason
These slides walk through the story of 1 Samuel. Samuel is the last judge of Israel. The people reject God and want a king. Saul is anointed as the first king, but he is not a good king. David, the shepherd boy is anointed and Saul is envious of him. David shows honor while Saul continues to self destruct.
How Barcodes Can Be Leveraged Within Odoo 17Celine George
In this presentation, we will explore how barcodes can be leveraged within Odoo 17 to streamline our manufacturing processes. We will cover the configuration steps, how to utilize barcodes in different manufacturing scenarios, and the overall benefits of implementing this technology.
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
Leveraging Generative AI to Drive Nonprofit InnovationTechSoup
In this webinar, participants learned how to utilize Generative AI to streamline operations and elevate member engagement. Amazon Web Service experts provided a customer specific use cases and dived into low/no-code tools that are quick and easy to deploy through Amazon Web Service (AWS.)
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...indexPub
The recent surge in pro-Palestine student activism has prompted significant responses from universities, ranging from negotiations and divestment commitments to increased transparency about investments in companies supporting the war on Gaza. This activism has led to the cessation of student encampments but also highlighted the substantial sacrifices made by students, including academic disruptions and personal risks. The primary drivers of these protests are poor university administration, lack of transparency, and inadequate communication between officials and students. This study examines the profound emotional, psychological, and professional impacts on students engaged in pro-Palestine protests, focusing on Generation Z's (Gen-Z) activism dynamics. This paper explores the significant sacrifices made by these students and even the professors supporting the pro-Palestine movement, with a focus on recent global movements. Through an in-depth analysis of printed and electronic media, the study examines the impacts of these sacrifices on the academic and personal lives of those involved. The paper highlights examples from various universities, demonstrating student activism's long-term and short-term effects, including disciplinary actions, social backlash, and career implications. The researchers also explore the broader implications of student sacrifices. The findings reveal that these sacrifices are driven by a profound commitment to justice and human rights, and are influenced by the increasing availability of information, peer interactions, and personal convictions. The study also discusses the broader implications of this activism, comparing it to historical precedents and assessing its potential to influence policy and public opinion. The emotional and psychological toll on student activists is significant, but their sense of purpose and community support mitigates some of these challenges. However, the researchers call for acknowledging the broader Impact of these sacrifices on the future global movement of FreePalestine.
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏)-𝐏𝐫𝐞𝐥𝐢𝐦𝐬
𝐃𝐢𝐬𝐜𝐮𝐬𝐬 𝐭𝐡𝐞 𝐄𝐏𝐏 𝐂𝐮𝐫𝐫𝐢𝐜𝐮𝐥𝐮𝐦 𝐢𝐧 𝐭𝐡𝐞 𝐏𝐡𝐢𝐥𝐢𝐩𝐩𝐢𝐧𝐞𝐬:
- Understand the goals and objectives of the Edukasyong Pantahanan at Pangkabuhayan (EPP) curriculum, recognizing its importance in fostering practical life skills and values among students. Students will also be able to identify the key components and subjects covered, such as agriculture, home economics, industrial arts, and information and communication technology.
𝐄𝐱𝐩𝐥𝐚𝐢𝐧 𝐭𝐡𝐞 𝐍𝐚𝐭𝐮𝐫𝐞 𝐚𝐧𝐝 𝐒𝐜𝐨𝐩𝐞 𝐨𝐟 𝐚𝐧 𝐄𝐧𝐭𝐫𝐞𝐩𝐫𝐞𝐧𝐞𝐮𝐫:
-Define entrepreneurship, distinguishing it from general business activities by emphasizing its focus on innovation, risk-taking, and value creation. Students will describe the characteristics and traits of successful entrepreneurs, including their roles and responsibilities, and discuss the broader economic and social impacts of entrepreneurial activities on both local and global scales.
Chapter wise All Notes of First year Basic Civil Engineering.pptxDenish Jangid
Chapter wise All Notes of First year Basic Civil Engineering
Syllabus
Chapter-1
Introduction to objective, scope and outcome the subject
Chapter 2
Introduction: Scope and Specialization of Civil Engineering, Role of civil Engineer in Society, Impact of infrastructural development on economy of country.
Chapter 3
Surveying: Object Principles & Types of Surveying; Site Plans, Plans & Maps; Scales & Unit of different Measurements.
Linear Measurements: Instruments used. Linear Measurement by Tape, Ranging out Survey Lines and overcoming Obstructions; Measurements on sloping ground; Tape corrections, conventional symbols. Angular Measurements: Instruments used; Introduction to Compass Surveying, Bearings and Longitude & Latitude of a Line, Introduction to total station.
Levelling: Instrument used Object of levelling, Methods of levelling in brief, and Contour maps.
Chapter 4
Buildings: Selection of site for Buildings, Layout of Building Plan, Types of buildings, Plinth area, carpet area, floor space index, Introduction to building byelaws, concept of sun light & ventilation. Components of Buildings & their functions, Basic concept of R.C.C., Introduction to types of foundation
Chapter 5
Transportation: Introduction to Transportation Engineering; Traffic and Road Safety: Types and Characteristics of Various Modes of Transportation; Various Road Traffic Signs, Causes of Accidents and Road Safety Measures.
Chapter 6
Environmental Engineering: Environmental Pollution, Environmental Acts and Regulations, Functional Concepts of Ecology, Basics of Species, Biodiversity, Ecosystem, Hydrological Cycle; Chemical Cycles: Carbon, Nitrogen & Phosphorus; Energy Flow in Ecosystems.
Water Pollution: Water Quality standards, Introduction to Treatment & Disposal of Waste Water. Reuse and Saving of Water, Rain Water Harvesting. Solid Waste Management: Classification of Solid Waste, Collection, Transportation and Disposal of Solid. Recycling of Solid Waste: Energy Recovery, Sanitary Landfill, On-Site Sanitation. Air & Noise Pollution: Primary and Secondary air pollutants, Harmful effects of Air Pollution, Control of Air Pollution. . Noise Pollution Harmful Effects of noise pollution, control of noise pollution, Global warming & Climate Change, Ozone depletion, Greenhouse effect
Text Books:
1. Palancharmy, Basic Civil Engineering, McGraw Hill publishers.
2. Satheesh Gopi, Basic Civil Engineering, Pearson Publishers.
3. Ketki Rangwala Dalal, Essentials of Civil Engineering, Charotar Publishing House.
4. BCP, Surveying volume 1
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Introdução à programação orientada para aspectos
1. Introdução à Programação Orientada para Aspectos Manuel Menezes de Sequeira http://www.google.com/profiles/MMSequeira DCTI ISCTE-IUL
2. Sumário Motivação Mais um paradigma da programação porquê? Orientação para aspectos Noções elementares de AspectJ Três aplicações Imposição de políticas e verificação de semântica Instrumentação UML dinâmico 2010-05-19 Introdução à Programação Orientada para Aspectos 2
4. Desenvolvimento Humanos em equipa Somos limitados Lidamos bem com pouca informação Comunicamos com dificuldade Erramos Desenvolvimento adaptado a humanos Abstracção: apenas o essencial em cada passo Encapsulamento: ocultar pormenores irrelevantes Decomposição: divisão do sistema em módulos 2010-05-19 Introdução à Programação Orientada para Aspectos 4
5. Decomposições Procedimental Rotinas (funções e procedimentos) Abordagem descendente ou ascendente Centrada nos Dados (ou Baseada em Objectos) Centrada em dados e operações manipuladoras Tipos abstractos de dados Orientada para Objectos Centrada em objectos: responsabilidade, colaboração e comportamento Baseada em classificação 2010-05-19 Introdução à Programação Orientada para Aspectos 5
6. Preocupações ou facetas (concerns) Requisitos funcionais Requisitos não funcionais Controlo de acessos Registo de operações Etc. Preocupações de implementação Protecção contra erros Auxílio à depuração Imposição de políticas de implementação Etc. 2010-05-19 Introdução à Programação Orientada para Aspectos 6 Resolvidas através políticas de desenvolvimento
7. Análise: decomposição principal Levantamento de requisitos Identificação de casos de uso (requisitos funcionais) Enumeração Descrição informal (estórias) Diagramas de sequência ou colaboração Glossário do domínio Modelo Diagrama de classes/objectos Diagrama de sequência Etc. 2010-05-19 Introdução à Programação Orientada para Aspectos 7
8. Tirania da decomposição principal Decomposição em objectos permite boa modularização de algumas preocupações Mas não de outras… Exemplo Objectos criados apenas em fábrica Política complexa de controlo de acesso Registo de operações (logging) Traçado da execução (tracing) 2010-05-19 Introdução à Programação Orientada para Aspectos 8
9. Problema Preocupações transversais a decomposição principal Emaranhamento – Várias preocupações no mesmo módulo Espalhamento – Mesma preocupação em vários módulos Necessidade de disciplina do programador: desastre… Código difícil de manter, actualizar, depurar, etc. Exemplo: Controlo de acesso em quase todos os métodos de quase todas as classes do domínio… 2010-05-19 Introdução à Programação Orientada para Aspectos 9
13. Mais um paradigma da programação porquê? 2010-05-19 Introdução à Programação Orientada para Aspectos 13
14. O que se pretende 2010-05-19 Introdução à Programação Orientada para Aspectos 14 ApplicationSession StandardSession SessionInterceptor ApplicationSession StandardSession SessionInterceptor private long lastAccessed = creationTime; private int inactiveInterval = -1; void accessed() { // set last accessed to thisAccessTime as it will be left over // from the previous access lastAccessed = thisAccessTime; thisAccessTime = System.currentTimeMillis(); validate(); } void validate() { // if we have an inactive interval, check to see if we've exceeded it if (inactiveInterval != -1) { int thisInterval = (int)(System.currentTimeMillis() - lastAccessed) / 1000; if (thisInterval > inactiveInterval) { invalidate(); } } } public long getLastAccessedTime() { if (valid) { return lastAccessed; } else { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } } public long getLastAccessedTime() { return lastAccessed; } private long lastAccessed = creationTime; void accessed() { // set last accessed to thisAccessTime as it will be left over // from the previous access lastAccessed = thisAccessTime; thisAccessTime = System.currentTimeMillis(); } void validate() { // if we have an inactive interval, check to see if // we've exceeded it if (inactiveInterval != -1) { int thisInterval = (int)(System.currentTimeMillis() - lastAccessed) / 1000; if (thisInterval > inactiveInterval) { invalidate(); ServerSessionManager ssm = ServerSessionManager.getManager(); ssm.removeSession(this); } } } private long lastAccessedTime = creationTime; /** * Return the last time the client sent a request associated with this * session, as the number of milliseconds since midnight, January 1, 1970 * GMT. Actions that your application takes, such as getting or setting * a value associated with the session, do not affect the access time. */ public long getLastAccessedTime() { return (this.lastAccessedTime); } this.lastAccessedTime = time; /** * Update the accessed time information for this session. This method * should be called by the context when a request comes in for a particular * session, even if the application does not reference it. */ public void access() { this.lastAccessedTime = this.thisAccessedTime; this.thisAccessedTime = System.currentTimeMillis(); this.isNew=false; } lastAccessedTime = 0L; lastAccessedTime = ((Long) stream.readObject()).longValue(); maxInactiveInterval = ((Integer) stream.readObject()).intValue(); isNew = ((Boolean) stream.readObject()).booleanValue(); stream.writeObject(new Long(lastAccessedTime)); sM.accessed(ctx, request, sessionId ); public void accessed( Context ctx, Request req, String id ) { ApplicationSession apS=(ApplicationSession)findSession( ctx, id); if( apS==null) return; ServerSession servS=apS.getServerSession(); servS.accessed(); apS.accessed(); // cache it - no need to compute it again req.setSession( apS ); } /** * Invalidate all sessions that have expired. */ private void processExpires() { long timeNow = System.currentTimeMillis(); Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { StandardSession session = (StandardSession) sessions[i]; if (!session.isValid()) continue; int maxInactiveInterval = session.getMaxInactiveInterval(); if (maxInactiveInterval < 0) continue; int timeIdle = // Truncate, do not round up (int) ((timeNow - session.getLastAccessedTime()) / 1000L); if (timeIdle >= maxInactiveInterval) session.expire(); } } /** * Mark the specified session's last accessed time. This should be * called for each request by a RequestInterceptor. * * @param session The session to be marked */ public void accessed(Context ctx, Request req, String id) { HttpSession session=findSession(ctx, id); if( session == null) return; if (session instanceof Session) ((Session) session).access(); // cache the HttpSession - avoid another find req.setSession( session ); } StandardManager package org.apache.tomcat.request; import org.apache.tomcat.core.*; import org.apache.tomcat.util.*; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.http.*; /** * Will process the request and determine the session Id, and set it * in the Request. * It also marks the session as accessed. * * This implementation only handles Cookies sessions, please extend or * add new interceptors for other methods. * */ public class SessionInterceptor extends BaseInterceptor implements RequestInterceptor { // GS, separates the session id from the jvm route static final char SESSIONID_ROUTE_SEP = '.'; int debug=0; ContextManager cm; public SessionInterceptor() { } public void setDebug( int i ) { System.out.println("Set debug to " + i); debug=i; } public void setContextManager( ContextManager cm ) { this.cm=cm; } public int requestMap(Request request ) { String sessionId = null; Cookie cookies[]=request.getCookies(); // assert !=null for( int i=0; i<cookies.length; i++ ) { Cookie cookie = cookies[i]; if (cookie.getName().equals("JSESSIONID")) { sessionId = cookie.getValue(); sessionId=validateSessionId(request, sessionId); if (sessionId!=null){ request.setRequestedSessionIdFromCookie(true); } } } String sig=";jsessionid="; int foundAt=-1; if( debug>0 ) cm.log(" XXX RURI=" + request.getRequestURI()); if ((foundAt=request.getRequestURI().indexOf(sig))!=-1){ sessionId=request.getRequestURI().substring(foundAt+sig.length()); // rewrite URL, do I need to do anything more? request.setRequestURI(request.getRequestURI().substring(0, foundAt)); sessionId=validateSessionId(request, sessionId); if (sessionId!=null){ request.setRequestedSessionIdFromURL(true); } } return 0; } // XXX what is the correct behavior if the session is invalid ? // We may still set it and just return session invalid. /** Validate and fix the session id. If the session is not valid return null. * It will also clean up the session from load-balancing strings. * @return sessionId, or null if not valid */ private String validateSessionId(Request request, String sessionId){ // GS, We piggyback the JVM id on top of the session cookie // Separate them ... if( debug>0 ) cm.log(" Orig sessionId " + sessionId ); if (null != sessionId) { int idex = sessionId.lastIndexOf(SESSIONID_ROUTE_SEP); if(idex > 0) { sessionId = sessionId.substring(0, idex); } } if (sessionId != null && sessionId.length()!=0) { // GS, We are in a problem here, we may actually get // multiple Session cookies (one for the root // context and one for the real context... or old session // cookie. We must check for validity in the current context. Context ctx=request.getContext(); SessionManager sM = ctx.getSessionManager(); if(null != sM.findSession(ctx, sessionId)) { sM.accessed(ctx, request, sessionId ); request.setRequestedSessionId(sessionId); if( debug>0 ) cm.log(" Final session id " + sessionId ); return sessionId; } } return null; } public int beforeBody( Request rrequest, Response response ) { String reqSessionId = response.getSessionId(); if( debug>0 ) cm.log("Before Body " + reqSessionId ); if( reqSessionId==null) return 0; // GS, set the path attribute to the cookie. This way // multiple session cookies can be used, one for each // context. String sessionPath = rrequest.getContext().getPath(); if(sessionPath.length() == 0) { sessionPath = "/"; } // GS, piggyback the jvm route on the session id. if(!sessionPath.equals("/")) { String jvmRoute = rrequest.getJvmRoute(); if(null != jvmRoute) { reqSessionId = reqSessionId + SESSIONID_ROUTE_SEP + jvmRoute; } } Cookie cookie = new Cookie("JSESSIONID", reqSessionId); cookie.setMaxAge(-1); cookie.setPath(sessionPath); cookie.setVersion(1); response.addHeader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie)); cookie.setVersion(0); response.addHeader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie)); return 0; } /** Notification of context shutdown */ public void contextShutdown( Context ctx ) throws TomcatException { if( ctx.getDebug() > 0 ) ctx.log("Removing sessions from " + ctx ); ctx.getSessionManager().removeSessions(ctx); } } StandardManager package org.apache.tomcat.request; import org.apache.tomcat.core.*; import org.apache.tomcat.util.*; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.http.*; /** * Will process the request and determine the session Id, and set it * in the Request. * It also marks the session as accessed. * * This implementation only handles Cookies sessions, please extend or * add new interceptors for other methods. * */ public class SessionInterceptor extends BaseInterceptor implements RequestInterceptor { // GS, separates the session id from the jvm route static final char SESSIONID_ROUTE_SEP = '.'; int debug=0; ContextManager cm; public SessionInterceptor() { } public void setDebug( int i ) { System.out.println("Set debug to " + i); debug=i; } public void setContextManager( ContextManager cm ) { this.cm=cm; } public int requestMap(Request request ) { String sessionId = null; Cookie cookies[]=request.getCookies(); // assert !=null for( int i=0; i<cookies.length; i++ ) { Cookie cookie = cookies[i]; if (cookie.getName().equals("JSESSIONID")) { sessionId = cookie.getValue(); sessionId=validateSessionId(request, sessionId); if (sessionId!=null){ request.setRequestedSessionIdFromCookie(true); } } } String sig=";jsessionid="; int foundAt=-1; if( debug>0 ) cm.log(" XXX RURI=" + request.getRequestURI()); if ((foundAt=request.getRequestURI().indexOf(sig))!=-1){ sessionId=request.getRequestURI().substring(foundAt+sig.length()); // rewrite URL, do I need to do anything more? request.setRequestURI(request.getRequestURI().substring(0, foundAt)); sessionId=validateSessionId(request, sessionId); if (sessionId!=null){ request.setRequestedSessionIdFromURL(true); } } return 0; } // XXX what is the correct behavior if the session is invalid ? // We may still set it and just return session invalid. /** Validate and fix the session id. If the session is not valid return null. * It will also clean up the session from load-balancing strings. * @return sessionId, or null if not valid */ private String validateSessionId(Request request, String sessionId){ // GS, We piggyback the JVM id on top of the session cookie // Separate them ... if( debug>0 ) cm.log(" Orig sessionId " + sessionId ); if (null != sessionId) { int idex = sessionId.lastIndexOf(SESSIONID_ROUTE_SEP); if(idex > 0) { sessionId = sessionId.substring(0, idex); } } if (sessionId != null && sessionId.length()!=0) { // GS, We are in a problem here, we may actually get // multiple Session cookies (one for the root // context and one for the real context... or old session // cookie. We must check for validity in the current context. Context ctx=request.getContext(); SessionManager sM = ctx.getSessionManager(); if(null != sM.findSession(ctx, sessionId)) { request.setRequestedSessionId(sessionId); if( debug>0 ) cm.log(" Final session id " + sessionId ); return sessionId; } } return null; } public int beforeBody( Request rrequest, Response response ) { String reqSessionId = response.getSessionId(); if( debug>0 ) cm.log("Before Body " + reqSessionId ); if( reqSessionId==null) return 0; // GS, set the path attribute to the cookie. This way // multiple session cookies can be used, one for each // context. String sessionPath = rrequest.getContext().getPath(); if(sessionPath.length() == 0) { sessionPath = "/"; } // GS, piggyback the jvm route on the session id. if(!sessionPath.equals("/")) { String jvmRoute = rrequest.getJvmRoute(); if(null != jvmRoute) { reqSessionId = reqSessionId + SESSIONID_ROUTE_SEP + jvmRoute; } } Cookie cookie = new Cookie("JSESSIONID", reqSessionId); cookie.setMaxAge(-1); cookie.setPath(sessionPath); cookie.setVersion(1); response.addHeader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie)); cookie.setVersion(0); response.addHeader( CookieTools.getCookieHeaderName(cookie), CookieTools.getCookieHeaderValue(cookie)); return 0; } /** Notification of context shutdown */ public void contextShutdown( Context ctx ) throws TomcatException { if( ctx.getDebug() > 0 ) ctx.log("Removing sessions from " + ctx ); ctx.getSessionManager().removeSessions(ctx); } } /* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.tomcat.session; import org.apache.tomcat.core.*; import org.apache.tomcat.util.StringManager; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /** * Core implementation of an application level session * * @author James Duncan Davidson [duncan@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] */ public class ApplicationSession implements HttpSession { private StringManager sm = StringManager.getManager("org.apache.tomcat.session"); private Hashtable values = new Hashtable(); private String id; private ServerSession serverSession; private Context context; private long creationTime = System.currentTimeMillis();; private long thisAccessTime = creationTime; private long lastAccessed = creationTime; private int inactiveInterval = -1; private boolean valid = true; ApplicationSession(String id, ServerSession serverSession, Context context) { this.serverSession = serverSession; this.context = context; this.id = id; this.inactiveInterval = context.getSessionTimeOut(); if (this.inactiveInterval != -1) { this.inactiveInterval *= 60; } } ServerSession getServerSession() { return serverSession; } /** * Called by context when request comes in so that accesses and * inactivities can be dealt with accordingly. */ void accessed() { // set last accessed to thisAccessTime as it will be left over // from the previous access lastAccessed = thisAccessTime; thisAccessTime = System.currentTimeMillis(); validate(); } void validate() { // if we have an inactive interval, check to see if we've exceeded it if (inactiveInterval != -1) { int thisInterval = (int)(System.currentTimeMillis() - lastAccessed) / 1000; if (thisInterval > inactiveInterval) { invalidate(); } } } // HTTP SESSION IMPLEMENTATION METHODS public String getId() { if (valid) { return id; } else { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } } public long getCreationTime() { if (valid) { return creationTime; } else { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } } /** * * @deprecated */ public HttpSessionContext getSessionContext() { return new SessionContextImpl(); } public long getLastAccessedTime() { if (valid) { return lastAccessed; } else { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } } public void invalidate() { serverSession.removeApplicationSession(context); // remove everything in the session Enumeration enum = values.keys(); while (enum.hasMoreElements()) { String name = (String)enum.nextElement(); removeValue(name); } valid = false; } public boolean isNew() { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (thisAccessTime == creationTime) { return true; } else { return false; } } /** * @deprecated */ public void putValue(String name, Object value) { setAttribute(name, value); } public void setAttribute(String name, Object value) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (name == null) { String msg = sm.getString("applicationSession.value.iae"); throw new IllegalArgumentException(msg); } removeValue(name); // remove any existing binding if (value != null && value instanceof HttpSessionBindingListener) { HttpSessionBindingEvent e = new HttpSessionBindingEvent(this, name); ((HttpSessionBindingListener)value).valueBound(e); } values.put(name, value); } /** * @deprecated */ public Object getValue(String name) { return getAttribute(name); } public Object getAttribute(String name) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (name == null) { String msg = sm.getString("applicationSession.value.iae"); throw new IllegalArgumentException(msg); } return values.get(name); } /** * @deprecated */ public String[] getValueNames() { Enumeration e = getAttributeNames(); Vector names = new Vector(); while (e.hasMoreElements()) { names.addElement(e.nextElement()); } String[] valueNames = new String[names.size()]; names.copyInto(valueNames); return valueNames; } public Enumeration getAttributeNames() { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } Hashtable valuesClone = (Hashtable)values.clone(); return (Enumeration)valuesClone.keys(); } /** * @deprecated */ public void removeValue(String name) { removeAttribute(name); } public void removeAttribute(String name) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (name == null) { String msg = sm.getString("applicationSession.value.iae"); throw new IllegalArgumentException(msg); } Object o = values.get(name); if (o instanceof HttpSessionBindingListener) { HttpSessionBindingEvent e = new HttpSessionBindingEvent(this,name); ((HttpSessionBindingListener)o).valueUnbound(e); } values.remove(name); } public void setMaxInactiveInterval(int interval) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } inactiveInterval = interval; } public int getMaxInactiveInterval() { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } return inactiveInterval; } } //----------------------------------------------------------------------- package org.apache.tomcat.session; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionContext; import org.apache.tomcat.catalina.*; import org.apache.tomcat.util.StringManager; /** * Standard implementation of the <b>Session</b> interface. This object is * serializable, so that it can be stored in persistent storage or transferred * to a different JVM for distributable session support. * <p> * <b>IMPLEMENTATION NOTE</b>: An instance of this class represents both the * internal (Session) and application level (HttpSession) view of the session. * However, because the class itself is not declared public, Java logic outside * of the <code>org.apache.tomcat.session</code> package cannot cast an * HttpSession view of this instance back to a Session view. * * @author Craig R. McClanahan * @version $Revision: 1.2 $ $Date: 2000/05/15 17:54:10 $ */ final class StandardSession implements HttpSession, Session { // ----------------------------------------------------------- Constructors /** * Construct a new Session associated with the specified Manager. * * @param manager The manager with which this Session is associated */ public StandardSession(Manager manager) { super(); this.manager = manager; } // ----------------------------------------------------- Instance Variables /** * The collection of user data attributes associated with this Session. */ private Hashtable attributes = new Hashtable(); /** * The time this session was created, in milliseconds since midnight, * January 1, 1970 GMT. */ private long creationTime = 0L; /** * The session identifier of this Session. */ private String id = null; /** * Descriptive information describing this Session implementation. */ private static final String info = "StandardSession/1.0"; /** * The last accessed time for this Session. */ private long lastAccessedTime = creationTime; /** * The Manager with which this Session is associated. */ private Manager manager = null; /** * The maximum time interval, in seconds, between client requests before * the servlet container may invalidate this session. A negative time * indicates that the session should never time out. */ private int maxInactiveInterval = -1; /** * Flag indicating whether this session is new or not. */ private boolean isNew = true; /** * Flag indicating whether this session is valid or not. */ private boolean isValid = false; /** * The string manager for this package. */ private StringManager sm = StringManager.getManager("org.apache.tomcat.session"); /** * The HTTP session context associated with this session. */ private static HttpSessionContext sessionContext = null; /** * The current accessed time for this session. */ private long thisAccessedTime = creationTime; // ----------------------------------------------------- Session Properties /** * Set the creation time for this session. This method is called by the * Manager when an existing Session instance is reused. * * @param time The new creation time */ public void setCreationTime(long time) { this.creationTime = time; this.lastAccessedTime = time; this.thisAccessedTime = time; } /** * Return the session identifier for this session. */ public String getId() { return (this.id); } /** * Set the session identifier for this session. * * @param id The new session identifier */ public void setId(String id) { if ((this.id != null) && (manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).remove(this); this.id = id; if ((manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).add(this); } /** * Return descriptive information about this Session implementation and * the corresponding version number, in the format * <code><description>/<version></code>. */ public String getInfo() { return (this.info); } /** * Return the last time the client sent a request associated with this * session, as the number of milliseconds since midnight, January 1, 1970 * GMT. Actions that your application takes, such as getting or setting * a value associated with the session, do not affect the access time. */ public long getLastAccessedTime() { return (this.lastAccessedTime); } /** * Return the Manager within which this Session is valid. */ public Manager getManager() { return (this.manager); } /** * Set the Manager within which this Session is valid. * * @param manager The new Manager */ public void setManager(Manager manager) { this.manager = manager; } /** * Return the maximum time interval, in seconds, between client requests * before the servlet container will invalidate the session. A negative * time indicates that the session should never time out. * * @exception IllegalStateException if this method is called on * an invalidated session */ public int getMaxInactiveInterval() { return (this.maxInactiveInterval); } /** * Set the maximum time interval, in seconds, between client requests * before the servlet container will invalidate the session. A negative * time indicates that the session should never time out. * * @param interval The new maximum interval */ public void setMaxInactiveInterval(int interval) { this.maxInactiveInterval = interval; } /** * Return the <code>HttpSession</code> for which this object * is the facade. */ public HttpSession getSession() { return ((HttpSession) this); } // ------------------------------------------------- Session Public Methods /** * Update the accessed time information for this session. This method * should be called by the context when a request comes in for a particular * session, even if the application does not reference it. */ public void access() { this.lastAccessedTime = this.thisAccessedTime; this.thisAccessedTime = System.currentTimeMillis(); this.isNew=false; } /** * Perform the internal processing required to invalidate this session, * without triggering an exception if the session has already expired. */ public void expire() { // Remove this session from our manager's active sessions if ((manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).remove(this); // Unbind any objects associated with this session Vector results = new Vector(); Enumeration attrs = getAttributeNames(); while (attrs.hasMoreElements()) { String attr = (String) attrs.nextElement(); results.addElement(attr); } Enumeration names = results.elements(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); removeAttribute(name); } // Mark this session as invalid setValid(false); } /** * Release all object references, and initialize instance variables, in * preparation for reuse of this object. */ public void recycle() { // Reset the instance variables associated with this Session attributes.clear(); creationTime = 0L; id = null; lastAccessedTime = 0L; manager = null; maxInactiveInterval = -1; isNew = true; isValid = false; // Tell our Manager that this Session has been recycled if ((manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).recycle(this); } // ------------------------------------------------ Session Package Methods /** * Return the <code>isValid</code> flag for this session. */ boolean isValid() { return (this.isValid); } /** * Set the <code>isNew</code> flag for this session. * * @param isNew The new value for the <code>isNew</code> flag */ void setNew(boolean isNew) { this.isNew = isNew; } /** * Set the <code>isValid</code> flag for this session. * * @param isValid The new value for the <code>isValid</code> flag */ void setValid(boolean isValid) { this.isValid = isValid; } // ------------------------------------------------- HttpSession Properties /** * Return the time when this session was created, in milliseconds since * midnight, January 1, 1970 GMT. * * @exception IllegalStateException if this method is called on an * invalidated session */ public long getCreationTime() { return (this.creationTime); } /** * Return the session context with which this session is associated. * * @deprecated As of Version 2.1, this method is deprecated and has no * replacement. It will be removed in a future version of the * Java Servlet API. */ public HttpSessionContext getSessionContext() { if (sessionContext == null) sessionContext = new StandardSessionContext(); return (sessionContext); } // ----------------------------------------------HttpSession Public Methods /** * Return the object bound with the specified name in this session, or * <code>null</code> if no object is bound with that name. * * @param name Name of the attribute to be returned * * @exception IllegalStateException if this method is called on an * invalidated session */ public Object getAttribute(String name) { return (attributes.get(name)); } /** * Return an <code>Enumeration</code> of <code>String</code> objects * containing the names of the objects bound to this session. * * @exception IllegalStateException if this method is called on an * invalidated session */ public Enumeration getAttributeNames() { return (attributes.keys()); } /** * Return the object bound with the specified name in this session, or * <code>null</code> if no object is bound with that name. * * @param name Name of the value to be returned * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>getAttribute()</code> */ public Object getValue(String name) { return (getAttribute(name)); } /** * Return the set of names of objects bound to this session. If there * are no such objects, a zero-length array is returned. * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>getAttributeNames()</code> */ public String[] getValueNames() { Vector results = new Vector(); Enumeration attrs = getAttributeNames(); while (attrs.hasMoreElements()) { String attr = (String) attrs.nextElement(); results.addElement(attr); } String names[] = new String[results.size()]; for (int i = 0; i < names.length; i++) names[i] = (String) results.elementAt(i); return (names); } /** * Invalidates this session and unbinds any objects bound to it. * * @exception IllegalStateException if this method is called on * an invalidated session */ public void invalidate() { // Cause this session to expire expire(); } /** * Return <code>true</code> if the client does not yet know about the * session, or if the client chooses not to join the session. For * example, if the server used only cookie-based sessions, and the client * has disabled the use of cookies, then a session would be new on each * request. * * @exception IllegalStateException if this method is called on an * invalidated session */ public boolean isNew() { return (this.isNew); } /** * Bind an object to this session, using the specified name. If an object * of the same name is already bound to this session, the object is * replaced. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueBound()</code> on the object. * * @param name Name to which the object is bound, cannot be null * @param value Object to be bound, cannot be null * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>setAttribute()</code> */ public void putValue(String name, Object value) { setAttribute(name, value); } /** * Remove the object bound with the specified name from this session. If * the session does not have an object bound with this name, this method * does nothing. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueUnbound()</code> on the object. * * @param name Name of the object to remove from this session. * * @exception IllegalStateException if this method is called on an * invalidated session */ public void removeAttribute(String name) { synchronized (attributes) { Object object = attributes.get(name); if (object == null) return; attributes.remove(name); // System.out.println( "Removing attribute " + name ); if (object instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) object).valueUnbound (new HttpSessionBindingEvent((HttpSession) this, name)); } } } /** * Remove the object bound with the specified name from this session. If * the session does not have an object bound with this name, this method * does nothing. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueUnbound()</code> on the object. * * @param name Name of the object to remove from this session. * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>removeAttribute()</code> */ public void removeValue(String name) { removeAttribute(name); } /** * Bind an object to this session, using the specified name. If an object * of the same name is already bound to this session, the object is * replaced. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueBound()</code> on the object. * * @param name Name to which the object is bound, cannot be null * @param value Object to be bound, cannot be null * * @exception IllegalArgumentException if an attempt is made to add a * non-serializable object in an environment marked distributable. * @exception IllegalStateException if this method is called on an * invalidated session */ public void setAttribute(String name, Object value) { if ((manager != null) && manager.getDistributable() && !(value instanceof Serializable)) throw new IllegalArgumentException (sm.getString("standardSession.setAttribute.iae")); synchronized (attributes) { removeAttribute(name); attributes.put(name, value); if (value instanceof HttpSessionBindingListener) ((HttpSessionBindingListener) value).valueBound (new HttpSessionBindingEvent((HttpSession) this, name)); } } // -------------------------------------------- HttpSession Private Methods /** * Read a serialized version of this session object from the specified * object input stream. * <p> * <b>IMPLEMENTATION NOTE</b>: The reference to the owning Manager * is not restored by this method, and must be set explicitly. * * @param stream The input stream to read from * * @exception ClassNotFoundException if an unknown class is specified * @exception IOException if an input/output error occurs */ private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) creationTime = ((Long) stream.readObject()).longValue(); id = (String) stream.readObject(); lastAccessedTime = ((Long) stream.readObject()).longValue(); maxInactiveInterval = ((Integer) stream.readObject()).intValue(); isNew = ((Boolean) stream.readObject()).booleanValue(); isValid = ((Boolean) stream.readObject()).booleanValue(); // Deserialize the attribute count and attribute values int n = ((Integer) stream.readObject()).intValue(); for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = (Object) stream.readObject(); attributes.put(name, value); } } /** * Write a serialized version of this session object to the specified * object output stream. * <p> * <b>IMPLEMENTATION NOTE</b>: The owning Manager will not be stored * in the serialized representation of this Session. After calling * <code>readObject()</code>, you must set the associated Manager * explicitly. * <p> * <b>IMPLEMENTATION NOTE</b>: Any attribute that is not Serializable * will be silently ignored. If you do not want any such attributes, * be sure the <code>distributable</code> property of our associated * Manager is set to <code>true</code>. * * @param stream The output stream to write to * * @exception IOException if an input/output error occurs */ private void writeObject(ObjectOutputStream stream) throws IOException { // Write the scalar instance variables (except Manager) stream.writeObject(new Long(creationTime)); stream.writeObject(id); stream.writeObject(new Long(lastAccessedTime)); stream.writeObject(new Integer(maxInactiveInterval)); stream.writeObject(new Boolean(isNew)); stream.writeObject(new Boolean(isValid)); // Accumulate the names of serializable attributes Vector results = new Vector(); Enumeration attrs = getAttributeNames(); while (attrs.hasMoreElements()) { String attr = (String) attrs.nextElement(); Object value = attributes.get(attr); if (value instanceof Serializable) results.addElement(attr); } // Serialize the attribute count and the attribute values stream.writeObject(new Integer(results.size())); Enumeration names = results.elements(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); stream.writeObject(name); stream.writeObject(attributes.get(name)); } } crosscut invalidate(StandardSession s): s & (int getMaxInactiveInterval() | long getCreationTime() | Object getAttribute(String) | Enumeration getAttributeNames() | String[] getValueNames() | void invalidate() | boolean isNew() | void removeAttribute(String) | void setAttribute(String, Object)); static advice(StandardSession s): invalidate(s) { before { if (!s.isValid()) throw new IllegalStateException (s.sm.getString("standardSession." + thisJoinPoint.methodName + ".ise")); } } } // -------------------------------------------------------------- Private Class /** * This class is a dummy implementation of the <code>HttpSessionContext</code> * interface, to conform to the requirement that such an object be returned * when <code>HttpSession.getSessionContext()</code> is called. * * @author Craig R. McClanahan * * @deprecated As of Java Servlet API 2.1 with no replacement. The * interface will be removed in a future version of this API. */ final class StandardSessionContext implements HttpSessionContext { private Vector dummy = new Vector(); /** * Return the session identifiers of all sessions defined * within this context. * * @deprecated As of Java Servlet API 2.1 with no replacement. * This method must return an empty <code>Enumeration</code> * and will be removed in a future version of the API. */ public Enumeration getIds() { return (dummy.elements()); } /** * Return the <code>HttpSession</code> associated with the * specified session identifier. * * @param id Session identifier for which to look up a session * * @deprecated As of Java Servlet API 2.1 with no replacement. * This method must return null and will be removed in a * future version of the API. */ public HttpSession getSession(String id) { return (null); } } StandardSessionManager /* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * [Additional notices, if required by prior licensing conditions] * */ package org.apache.tomcat.session; import org.apache.tomcat.core.*; import org.apache.tomcat.util.StringManager; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /** * Core implementation of an application level session * * @author James Duncan Davidson [duncan@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] */ public class ApplicationSession implements HttpSession { private StringManager sm = StringManager.getManager("org.apache.tomcat.session"); private Hashtable values = new Hashtable(); private String id; private ServerSession serverSession; private Context context; private long creationTime = System.currentTimeMillis();; private long thisAccessTime = creationTime; private boolean valid = true; ApplicationSession(String id, ServerSession serverSession, Context context) { this.serverSession = serverSession; this.context = context; this.id = id; this.inactiveInterval = context.getSessionTimeOut(); if (this.inactiveInterval != -1) { this.inactiveInterval *= 60; } } ServerSession getServerSession() { return serverSession; } /** * Called by context when request comes in so that accesses and * inactivities can be dealt with accordingly. */ // HTTP SESSION IMPLEMENTATION METHODS public String getId() { if (valid) { return id; } else { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } } public long getCreationTime() { if (valid) { return creationTime; } else { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } } /** * * @deprecated */ public HttpSessionContext getSessionContext() { return new SessionContextImpl(); } public void invalidate() { serverSession.removeApplicationSession(context); // remove everything in the session Enumeration enum = values.keys(); while (enum.hasMoreElements()) { String name = (String)enum.nextElement(); removeValue(name); } valid = false; } public boolean isNew() { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (thisAccessTime == creationTime) { return true; } else { return false; } } /** * @deprecated */ public void putValue(String name, Object value) { setAttribute(name, value); } public void setAttribute(String name, Object value) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (name == null) { String msg = sm.getString("applicationSession.value.iae"); throw new IllegalArgumentException(msg); } removeValue(name); // remove any existing binding if (value != null && value instanceof HttpSessionBindingListener) { HttpSessionBindingEvent e = new HttpSessionBindingEvent(this, name); ((HttpSessionBindingListener)value).valueBound(e); } values.put(name, value); } /** * @deprecated */ public Object getValue(String name) { return getAttribute(name); } public Object getAttribute(String name) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (name == null) { String msg = sm.getString("applicationSession.value.iae"); throw new IllegalArgumentException(msg); } return values.get(name); } /** * @deprecated */ public String[] getValueNames() { Enumeration e = getAttributeNames(); Vector names = new Vector(); while (e.hasMoreElements()) { names.addElement(e.nextElement()); } String[] valueNames = new String[names.size()]; names.copyInto(valueNames); return valueNames; } public Enumeration getAttributeNames() { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } Hashtable valuesClone = (Hashtable)values.clone(); return (Enumeration)valuesClone.keys(); } /** * @deprecated */ public void removeValue(String name) { removeAttribute(name); } public void removeAttribute(String name) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } if (name == null) { String msg = sm.getString("applicationSession.value.iae"); throw new IllegalArgumentException(msg); } Object o = values.get(name); if (o instanceof HttpSessionBindingListener) { HttpSessionBindingEvent e = new HttpSessionBindingEvent(this,name); ((HttpSessionBindingListener)o).valueUnbound(e); } values.remove(name); } public void setMaxInactiveInterval(int interval) { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } inactiveInterval = interval; } public int getMaxInactiveInterval() { if (! valid) { String msg = sm.getString("applicationSession.session.ise"); throw new IllegalStateException(msg); } return inactiveInterval; } } //----------------------------------------------------------------------- package org.apache.tomcat.session; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionContext; import org.apache.tomcat.catalina.*; import org.apache.tomcat.util.StringManager; /** * Standard implementation of the <b>Session</b> interface. This object is * serializable, so that it can be stored in persistent storage or transferred * to a different JVM for distributable session support. * <p> * <b>IMPLEMENTATION NOTE</b>: An instance of this class represents both the * internal (Session) and application level (HttpSession) view of the session. * However, because the class itself is not declared public, Java logic outside * of the <code>org.apache.tomcat.session</code> package cannot cast an * HttpSession view of this instance back to a Session view. * * @author Craig R. McClanahan * @version $Revision: 1.2 $ $Date: 2000/05/15 17:54:10 $ */ final class StandardSession implements HttpSession, Session { // ----------------------------------------------------------- Constructors /** * Construct a new Session associated with the specified Manager. * * @param manager The manager with which this Session is associated */ public StandardSession(Manager manager) { super(); this.manager = manager; } // ----------------------------------------------------- Instance Variables /** * The collection of user data attributes associated with this Session. */ private Hashtable attributes = new Hashtable(); /** * The time this session was created, in milliseconds since midnight, * January 1, 1970 GMT. */ private long creationTime = 0L; /** * The session identifier of this Session. */ private String id = null; /** * Descriptive information describing this Session implementation. */ private static final String info = "StandardSession/1.0"; /** * The last accessed time for this Session. */ /** * The Manager with which this Session is associated. */ private Manager manager = null; /** * The maximum time interval, in seconds, between client requests before * the servlet container may invalidate this session. A negative time * indicates that the session should never time out. */ private int maxInactiveInterval = -1; /** * Flag indicating whether this session is new or not. */ private boolean isNew = true; /** * Flag indicating whether this session is valid or not. */ private boolean isValid = false; /** * The string manager for this package. */ private StringManager sm = StringManager.getManager("org.apache.tomcat.session"); /** * The HTTP session context associated with this session. */ private static HttpSessionContext sessionContext = null; /** * The current accessed time for this session. */ private long thisAccessedTime = creationTime; // ----------------------------------------------------- Session Properties /** * Set the creation time for this session. This method is called by the * Manager when an existing Session instance is reused. * * @param time The new creation time */ public void setCreationTime(long time) { this.creationTime = time; this.thisAccessedTime = time; } /** * Return the session identifier for this session. */ public String getId() { return (this.id); } /** * Set the session identifier for this session. * * @param id The new session identifier */ public void setId(String id) { if ((this.id != null) && (manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).remove(this); this.id = id; if ((manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).add(this); } /** * Return descriptive information about this Session implementation and * the corresponding version number, in the format * <code><description>/<version></code>. */ public String getInfo() { return (this.info); } /** * Return the Manager within which this Session is valid. */ public Manager getManager() { return (this.manager); } /** * Set the Manager within which this Session is valid. * * @param manager The new Manager */ public void setManager(Manager manager) { this.manager = manager; } /** * Return the maximum time interval, in seconds, between client requests * before the servlet container will invalidate the session. A negative * time indicates that the session should never time out. * * @exception IllegalStateException if this method is called on * an invalidated session */ public int getMaxInactiveInterval() { return (this.maxInactiveInterval); } /** * Set the maximum time interval, in seconds, between client requests * before the servlet container will invalidate the session. A negative * time indicates that the session should never time out. * * @param interval The new maximum interval */ public void setMaxInactiveInterval(int interval) { this.maxInactiveInterval = interval; } /** * Return the <code>HttpSession</code> for which this object * is the facade. */ public HttpSession getSession() { return ((HttpSession) this); } // ------------------------------------------------- Session Public Methods /** * Perform the internal processing required to invalidate this session, * without triggering an exception if the session has already expired. */ public void expire() { // Remove this session from our manager's active sessions if ((manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).remove(this); // Unbind any objects associated with this session Vector results = new Vector(); Enumeration attrs = getAttributeNames(); while (attrs.hasMoreElements()) { String attr = (String) attrs.nextElement(); results.addElement(attr); } Enumeration names = results.elements(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); removeAttribute(name); } // Mark this session as invalid setValid(false); } /** * Release all object references, and initialize instance variables, in * preparation for reuse of this object. */ public void recycle() { // Reset the instance variables associated with this Session attributes.clear(); creationTime = 0L; id = null; manager = null; maxInactiveInterval = -1; isNew = true; isValid = false; // Tell our Manager that this Session has been recycled if ((manager != null) && (manager instanceof ManagerBase)) ((ManagerBase) manager).recycle(this); } // ------------------------------------------------ Session Package Methods /** * Return the <code>isValid</code> flag for this session. */ boolean isValid() { return (this.isValid); } /** * Set the <code>isNew</code> flag for this session. * * @param isNew The new value for the <code>isNew</code> flag */ void setNew(boolean isNew) { this.isNew = isNew; } /** * Set the <code>isValid</code> flag for this session. * * @param isValid The new value for the <code>isValid</code> flag */ void setValid(boolean isValid) { this.isValid = isValid; } // ------------------------------------------------- HttpSession Properties /** * Return the time when this session was created, in milliseconds since * midnight, January 1, 1970 GMT. * * @exception IllegalStateException if this method is called on an * invalidated session */ public long getCreationTime() { return (this.creationTime); } /** * Return the session context with which this session is associated. * * @deprecated As of Version 2.1, this method is deprecated and has no * replacement. It will be removed in a future version of the * Java Servlet API. */ public HttpSessionContext getSessionContext() { if (sessionContext == null) sessionContext = new StandardSessionContext(); return (sessionContext); } // ----------------------------------------------HttpSession Public Methods /** * Return the object bound with the specified name in this session, or * <code>null</code> if no object is bound with that name. * * @param name Name of the attribute to be returned * * @exception IllegalStateException if this method is called on an * invalidated session */ public Object getAttribute(String name) { return (attributes.get(name)); } /** * Return an <code>Enumeration</code> of <code>String</code> objects * containing the names of the objects bound to this session. * * @exception IllegalStateException if this method is called on an * invalidated session */ public Enumeration getAttributeNames() { return (attributes.keys()); } /** * Return the object bound with the specified name in this session, or * <code>null</code> if no object is bound with that name. * * @param name Name of the value to be returned * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>getAttribute()</code> */ public Object getValue(String name) { return (getAttribute(name)); } /** * Return the set of names of objects bound to this session. If there * are no such objects, a zero-length array is returned. * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>getAttributeNames()</code> */ public String[] getValueNames() { Vector results = new Vector(); Enumeration attrs = getAttributeNames(); while (attrs.hasMoreElements()) { String attr = (String) attrs.nextElement(); results.addElement(attr); } String names[] = new String[results.size()]; for (int i = 0; i < names.length; i++) names[i] = (String) results.elementAt(i); return (names); } /** * Invalidates this session and unbinds any objects bound to it. * * @exception IllegalStateException if this method is called on * an invalidated session */ public void invalidate() { // Cause this session to expire expire(); } /** * Return <code>true</code> if the client does not yet know about the * session, or if the client chooses not to join the session. For * example, if the server used only cookie-based sessions, and the client * has disabled the use of cookies, then a session would be new on each * request. * * @exception IllegalStateException if this method is called on an * invalidated session */ public boolean isNew() { return (this.isNew); } /** * Bind an object to this session, using the specified name. If an object * of the same name is already bound to this session, the object is * replaced. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueBound()</code> on the object. * * @param name Name to which the object is bound, cannot be null * @param value Object to be bound, cannot be null * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>setAttribute()</code> */ public void putValue(String name, Object value) { setAttribute(name, value); } /** * Remove the object bound with the specified name from this session. If * the session does not have an object bound with this name, this method * does nothing. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueUnbound()</code> on the object. * * @param name Name of the object to remove from this session. * * @exception IllegalStateException if this method is called on an * invalidated session */ public void removeAttribute(String name) { synchronized (attributes) { Object object = attributes.get(name); if (object == null) return; attributes.remove(name); // System.out.println( "Removing attribute " + name ); if (object instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) object).valueUnbound (new HttpSessionBindingEvent((HttpSession) this, name)); } } } /** * Remove the object bound with the specified name from this session. If * the session does not have an object bound with this name, this method * does nothing. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueUnbound()</code> on the object. * * @param name Name of the object to remove from this session. * * @exception IllegalStateException if this method is called on an * invalidated session * * @deprecated As of Version 2.2, this method is replaced by * <code>removeAttribute()</code> */ public void removeValue(String name) { removeAttribute(name); } /** * Bind an object to this session, using the specified name. If an object * of the same name is already bound to this session, the object is * replaced. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>valueBound()</code> on the object. * * @param name Name to which the object is bound, cannot be null * @param value Object to be bound, cannot be null * * @exception IllegalArgumentException if an attempt is made to add a * non-serializable object in an environment marked distributable. * @exception IllegalStateException if this method is called on an * invalidated session */ public void setAttribute(String name, Object value) { if ((manager != null) && manager.getDistributable() && !(value instanceof Serializable)) throw new IllegalArgumentException (sm.getString("standardSession.setAttribute.iae")); synchronized (attributes) { removeAttribute(name); attributes.put(name, value); if (value instanceof HttpSessionBindingListener) ((HttpSessionBindingListener) value).valueBound (new HttpSessionBindingEvent((HttpSession) this, name)); } } // -------------------------------------------- HttpSession Private Methods /** * Read a serialized version of this session object from the specified * object input stream. * <p> * <b>IMPLEMENTATION NOTE</b>: The reference to the owning Manager * is not restored by this method, and must be set explicitly. * * @param stream The input stream to read from * * @exception ClassNotFoundException if an unknown class is specified * @exception IOException if an input/output error occurs */ private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { // Deserialize the scalar instance variables (except Manager) creationTime = ((Long) stream.readObject()).longValue(); id = (String) stream.readObject(); isValid = ((Boolean) stream.readObject()).booleanValue(); // Deserialize the attribute count and attribute values int n = ((Integer) stream.readObject()).intValue(); for (int i = 0; i < n; i++) { String name = (String) stream.readObject(); Object value = (Object) stream.readObject(); attributes.put(name, value); } } /** * Write a serialized version of this session object to the specified * object output stream. * <p> * <b>IMPLEMENTATION NOTE</b>: The owning Manager will not be stored * in the serialized representation of this Session. After calling * <code>readObject()</code>, you must set the associated Manager * explicitly. * <p> * <b>IMPLEMENTATION NOTE</b>: Any attribute that is not Serializable * will be silently ignored. If you do not want any such attributes, * be sure the <code>distributable</code> property of our associated * Manager is set to <code>true</code>. * * @param stream The output stream to write to * * @exception IOException if an input/output error occurs */ private void writeObject(ObjectOutputStream stream) throws IOException { // Write the scalar instance variables (except Manager) stream.writeObject(new Long(creationTime)); stream.writeObject(id); stream.writeObject(new Integer(maxInactiveInterval)); stream.writeObject(new Boolean(isNew)); stream.writeObject(new Boolean(isValid)); // Accumulate the names of serializable attributes Vector results = new Vector(); Enumeration attrs = getAttributeNames(); while (attrs.hasMoreElements()) { String attr = (String) attrs.nextElement(); Object value = attributes.get(attr); if (value instanceof Serializable) results.addElement(attr); } // Serialize the attribute count and the attribute values stream.writeObject(new Integer(results.size())); Enumeration names = results.elements(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); stream.writeObject(name); stream.writeObject(attributes.get(name)); } } crosscut invalidate(StandardSession s): s & (int getMaxInactiveInterval() | long getCreationTime() | Object getAttribute(String) | Enumeration getAttributeNames() | String[] getValueNames() | void invalidate() | boolean isNew() | void removeAttribute(String) | void setAttribute(String, Object)); static advice(StandardSession s): invalidate(s) { before { if (!s.isValid()) throw new IllegalStateException (s.sm.getString("standardSession." + thisJoinPoint.methodName + ".ise")); } } } // -------------------------------------------------------------- Private Class /** * This class is a dummy implementation of the <code>HttpSessionContext</code> * interface, to conform to the requirement that such an object be returned * when <code>HttpSession.getSessionContext()</code> is called. * * @author Craig R. McClanahan * * @deprecated As of Java Servlet API 2.1 with no replacement. The * interface will be removed in a future version of this API. */ final class StandardSessionContext implements HttpSessionContext { private Vector dummy = new Vector(); /** * Return the session identifiers of all sessions defined * within this context. * * @deprecated As of Java Servlet API 2.1 with no replacement. * This method must return an empty <code>Enumeration</code> * and will be removed in a future version of the API. */ public Enumeration getIds() { return (dummy.elements()); } /** * Return the <code>HttpSession</code> associated with the * specified session identifier. * * @param id Session identifier for which to look up a session * * @deprecated As of Java Servlet API 2.1 with no replacement. * This method must return null and will be removed in a * future version of the API. */ public HttpSession getSession(String id) { return (null); } } StandardSessionManager package org.apache.tomcat.session; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.apache.tomcat.catalina.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.apache.tomcat.util.StringManager; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * Standard implementation of the <b>Manager</b> interface that provides * no session persistence or distributable capabilities, but does support * an optional, configurable, maximum number of active sessions allowed. * <p> * Lifecycle configuration of this component assumes an XML node * in the following format: * <code> * <Manager className="org.apache.tomcat.session.StandardManager" * checkInterval="60" maxActiveSessions="-1" * maxInactiveInterval="-1" /> * </code> * where you can adjust the following parameters, with default values * in square brackets: * <ul> * <li><b>checkInterval</b> - The interval (in seconds) between background * thread checks for expired sessions. [60] * <li><b>maxActiveSessions</b> - The maximum number of sessions allowed to * be active at once, or -1 for no limit. [-1] * <li><b>maxInactiveInterval</b> - The default maximum number of seconds of * inactivity before which the servlet container is allowed to time out * a session, or -1 for no limit. This value should be overridden from * the default session timeout specified in the web application deployment * descriptor, if any. [-1] * </ul> * * @author Craig R. McClanahan * @version $Revision: 1.1.1.1 $ $Date: 2000/05/02 21:28:30 $ */ public final class StandardManager extends ManagerBase implements Lifecycle, Runnable { // ----------------------------------------------------- Instance Variables /** * The interval (in seconds) between checks for expired sessions. */ private int checkInterval = 60; /** * Has this component been configured yet? */ private boolean configured = false; /** * The descriptive information about this implementation. */ private static final String info = "StandardManager/1.0"; /** * The maximum number of active Sessions allowed, or -1 for no limit. */ protected int maxActiveSessions = -1; /** * The string manager for this package. */ private StringManager sm = StringManager.getManager("org.apache.tomcat.session"); /** * Has this component been started yet? */ private boolean started = false; /** * The background thread. */ private Thread thread = null; /** * The background thread completion semaphore. */ private boolean threadDone = false; /** * Name to register for the background thread. */ private String threadName = "StandardManager"; // ------------------------------------------------------------- Properties /** * Return the check interval (in seconds) for this Manager. */ public int getCheckInterval() { return (this.checkInterval); } /** * Set the check interval (in seconds) for this Manager. * * @param checkInterval The new check interval */ public void setCheckInterval(int checkInterval) { this.checkInterval = checkInterval; } /** * Return descriptive information about this Manager implementation and * the corresponding version number, in the format * <code><description>/<version></code>. */ public String getInfo() { return (this.info); } /** * Return the maximum number of active Sessions allowed, or -1 for * no limit. */ public int getMaxActiveSessions() { return (this.maxActiveSessions); } /** * Set the maximum number of actives Sessions allowed, or -1 for * no limit. * * @param max The new maximum number of sessions */ public void setMaxActiveSessions(int max) { this.maxActiveSessions = max; } // --------------------------------------------------------- Public Methods /** * Construct and return a new session object, based on the default * settings specified by this Manager's properties. The session * id will be assigned by this method, and available via the getId() * method of the returned session. If a new session cannot be created * for any reason, return <code>null</code>. * * @exception IllegalStateException if a new session cannot be * instantiated for any reason */ public Session createSession() { if ((maxActiveSessions >= 0) && (sessions.size() >= maxActiveSessions)) throw new IllegalStateException (sm.getString("standardManager.createSession.ise")); return (super.createSession()); } // ------------------------------------------------------ Lifecycle Methods /** * Configure this component, based on the specified configuration * parameters. This method should be called immediately after the * component instance is created, and before <code>start()</code> * is called. * * @param parameters Configuration parameters for this component * (<B>FIXME: What object type should this really be?) * * @exception IllegalStateException if this component has already been * configured and/or started * @exception LifecycleException if this component detects a fatal error * in the configuration parameters it was given */ public void configure(Node parameters) throws LifecycleException { // Validate and update our current component state if (configured) throw new LifecycleException (sm.getString("standardManager.alreadyConfigured")); configured = true; if (parameters == null) return; // Parse and process our configuration parameters if (!("