### jwebserver Starting Example Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jwebserver Demonstrates the default invocation of the jwebserver command. When run without any options, it starts the server using default settings, typically binding to the loopback address and port 8000, serving the current directory. ```bash $ jwebserver ``` -------------------------------- ### FileSystemProvider.installedProviders() - Get Providers Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/class-use/List Returns a list of all installed file system providers available in the Java runtime. Each provider is represented by a FileSystemProvider object. ```APIDOC static List FileSystemProvider.installedProviders() - Returns a list of the installed file system providers. - Returns: A List of FileSystemProvider objects. ``` -------------------------------- ### Basic Timer Setup Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/Timer Demonstrates how to create and start a javax.swing.Timer that fires an ActionEvent once per second. It shows the delay setup and the ActionListener implementation. ```Java int delay = 1000; //milliseconds ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { //...Perform a task... } }; new Timer(delay, taskPerformer).start(); ``` -------------------------------- ### HttpServer Creation, Binding, and Starting Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.httpserver/com/sun/net/httpserver/HttpServer Provides documentation for essential HttpServer methods: creating a server with an initial context, binding it to an address and backlog, and starting its operation. Includes parameter details, return values, and potential exceptions. ```APIDOC HttpServer Methods: create public static HttpServer create(InetSocketAddress addr, int backlog, String path, HttpHandler handler, Filter... filters) throws IOException Creates an HttpServer instance with an initial context. The server is created with an *initial context* that maps the URI `path` to the exchange `handler`. The `filters`, if any, are added to the initial context. The returned server is not started so can be configured further. Parameters: addr: The address to listen on, if `null` then `bind(InetSocketAddress, int)` must be called to set the address. backlog: The socket backlog. If this value is less than or equal to zero, then a system default value is used. path: The root URI path of the context, must be absolute. handler: The HttpHandler for the context. filters: The Filters for the context, optional. Returns: The HttpServer instance. Throws: IOException: If an I/O error occurs. BindException: If the server cannot bind to the address. IllegalArgumentException: If path is invalid. NullPointerException: If `path`, `handler`, `filters`, or any element of `filters` are `null`. Since: 18 bind public abstract void bind(InetSocketAddress addr, int backlog) throws IOException Binds a currently unbound `HttpServer` to the given address and port number. A maximum backlog can also be specified. Parameters: addr: The address to listen on. backlog: The socket backlog. If this value is less than or equal to zero, then a system default value is used. Throws: BindException: If the server cannot bind to the requested address or if the server is already bound. NullPointerException: If addr is `null`. IOException: If an I/O error occurs. start public abstract void start() Starts this server in a new background thread. The background thread inherits the priority, thread group and context class loader of the caller. ``` -------------------------------- ### Java JVM Startup Command Example Source: https://docs.oracle.com/en/java/javase/21/docs/specs/unnamed-classes-instance-main-methods-jls Demonstrates how to start the Java Virtual Machine using a command-line invocation. It specifies the main class and passes arguments to the `main` method. ```Shell java Test reboot Bob Dot Enzo ``` -------------------------------- ### Get Selection Start Offset Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/accessibility/AccessibleText Returns the start offset within the selected text. ```APIDOC getSelectionStart: int getSelectionStart() Returns the start offset within the selected text. ``` -------------------------------- ### Get Installed FileSystem Providers (Java) Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/file/spi/FileSystemProvider Returns a list of all installed file system providers. The first invocation initializes the default provider and loads any other installed providers. ```APIDOC public static List installedProviders() Returns a list of the installed file system providers. The list contains at least one element, that is the default file system provider. Throws: ServiceConfigurationError - When an error occurs while loading a service provider. ``` -------------------------------- ### LaunchingConnector Interface and Launch Method Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.jdi/com/sun/jdi/connect/LaunchingConnector Provides documentation for the Java `LaunchingConnector` interface, which enables launching a target VM before connecting. It details the `launch` method, its parameters, return values, and potential exceptions. ```APIDOC LaunchingConnector Interface: Extends: Connector Since: 1.3 Description: A connector which can launch a target VM before connecting to it. Method: launch Signature: VirtualMachine launch(Map arguments) Throws: IOException: when unable to launch. Specific exceptions are dependent on the Connector implementation in use. IllegalConnectorArgumentsException: when one of the connector arguments is invalid. VMStartException: when the VM was successfully launched, but terminated with an error before a connection could be established. Description: Launches an application and connects to its VM. Properties of the launch (possibly including options, main class, and arguments) are specified in `arguments`. The argument map associates argument name strings to instances of `Connector.Argument`. The default argument map for a connector can be obtained through `Connector.defaultArguments()`. Argument map values can be changed, but map entries should not be added or deleted. Important note: If a target VM is launched through this function, its output and error streams must be read as it executes. These streams are available through the `Process` object returned by `VirtualMachine.process()`. If the streams are not periodically read, the target VM will stop executing when the buffers for these streams are filled. Parameters: arguments: the argument map to be used in launching the VM. Returns: the `VirtualMachine` mirror of the target VM. ``` -------------------------------- ### BasicInternalFrameTitlePane Lifecycle and Setup Methods Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/plaf/basic/BasicInternalFrameTitlePane Groups methods related to the installation, uninstallation, and setup of the title pane and its components, listeners, and defaults. ```APIDOC installTitlePane(): void Installs the title pane. addSubComponents(): void Adds subcomponents to the title pane. createActions(): void Creates the action objects for the title pane buttons. installListeners(): void Registers listeners for the title pane. uninstallListeners(): void Unregisters listeners from the title pane. installDefaults(): void Installs default properties for the title pane. uninstallDefaults(): void Uninstalls default properties from the title pane. createButtons(): void Creates the buttons (close, minimize, maximize) for the title pane. setButtonIcons(): void Sets the icons for the title pane buttons. assembleSystemMenu(): void Assembles the system menu for the title pane. addSystemMenuItems(JMenu systemMenu): void Adds system menu items to the provided `systemMenu`. createSystemMenu(): JMenu Returns a new instance of `JMenu` for the system menu. createSystemMenuBar(): void Creates the system menu bar. ``` -------------------------------- ### Create and Start Simple File Server Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.httpserver/com/sun/net/httpserver/SimpleFileServer Demonstrates creating and starting an HTTP file server using SimpleFileServer.createFileServer. It binds to an address, serves files from a path, and logs INFO level messages. ```java var addr = new InetSocketAddress(8080); var server = SimpleFileServer.createFileServer(addr, Path.of("/some/path"), OutputLevel.INFO); server.start(); ``` -------------------------------- ### SourcePositions API: Get Start Position Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.compiler/com/sun/source/tree/class-use/CompilationUnitTree Methods to retrieve the starting position of a tree within a comment or a file. ```APIDOC SourcePositions.getStartPosition(com.sun.source.doctree.DocCommentTree comment, com.sun.source.doctree.DocTree tree) Returns the starting position of the tree within the comment within the file. Returns: long SourcePositions.getStartPosition(com.sun.source.tree.CompilationUnitTree file, com.sun.source.tree.Tree tree) Returns the starting position of tree within file. Returns: long ``` -------------------------------- ### Get Selection Start Index in AccessibleText Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/AbstractButton.AccessibleAbstractButton Returns the starting offset of the currently selected text. If no text is selected, it returns the caret's position. ```APIDOC getSelectionStart() Returns the start offset within the selected text. If there is no selection, but there is a caret, the start and end offsets will be the same. Returns: the index into the text of the start of the selection Since: 1.3 ``` -------------------------------- ### JMXConnectorFactory connect example Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.management/javax/management/remote/JMXConnectorFactory Example demonstrating the creation of a JMXConnector using the connect method with environment properties. ```java JMXConnector conn = JMXConnectorFactory.newJMXConnector(serviceURL, environment); conn.connect(environment); ``` -------------------------------- ### Get Accessible Object Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.accessibility/com/sun/java/accessibility/util/Translator An example demonstrating how an assistive technology might use the `Translator.getAccessible` method to obtain an `Accessible` object for a given object. ```java Accessible accessible = Translator.getAccessible(someObj); // obtain information from the 'accessible' object. ``` -------------------------------- ### Navigation Link Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/plaf/synth/class-use/SynthLabelUI An example of a navigation link, common in web documentation, with a skip link functionality. ```html [Skip navigation links](#skip-navbar-top "Skip navigation links") ``` -------------------------------- ### jlink Options File Example Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jlink An example of an options file used with the jlink command to specify module path, modules to add, and output directory. ```properties #Wed Dec 07 00:40:19 EST 2016 --module-path mlib --add-modules com.greetings --output greetingsapp ``` -------------------------------- ### Get Available Locales Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/text/NumberFormat Retrieves an array of all locales supported by the `get*Instance` methods of this class. This includes locales supported by the Java runtime and installed providers. ```APIDOC public static Locale[] getAvailableLocales() Returns an array of all locales for which the get*Instance methods of this class can return localized instances. Returns: An array of locales for which localized NumberFormat instances are available. At a minimum, the returned array must contain a Locale instance equal to Locale.ROOT and a Locale instance equal to Locale.US. ``` -------------------------------- ### Example: javac Argument Files (Windows) Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/javac Demonstrates how to use two argument files for javac on Windows, one for options and one for source files, including paths with spaces. ```Java // options file content: // -d classes // -g // -sourcepath C:\java\pubs\ws\1.3\src\share\classes // sources file content: // MyClass1.java // MyClass2.java // MyClass3.java // Command to execute: // javac @options @sources ``` -------------------------------- ### Get Ticket Start Time Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.security.jgss/javax/security/auth/kerberos/KerberosTicket Retrieves the start time for the ticket's validity period. Returns null if the field is not set or the ticket is destroyed. ```APIDOC getStartTime(): Date Returns the start time for this ticket's validity period. Returns: the start time for this ticket's validity period or null if the field is not set or this ticket is destroyed. ``` -------------------------------- ### Java APIDOC: Get Selection Start Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/ProgressMonitor.AccessibleProgressMonitor Returns the start offset of the currently selected text. The offset is zero-based and inclusive of the character at the offset. ```APIDOC getSelectionStart() Description: Returns the start offset within the selected text. Returns: int ``` -------------------------------- ### Java ConnectionBuilder Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/ConnectionBuilder Example demonstrating how to use the `ConnectionBuilder` to create a database connection with user, password, and sharding key configurations. ```java DataSource ds = new MyDataSource(); ShardingKey superShardingKey = ds.createShardingKeyBuilder() .subkey("EASTERN_REGION", JDBCType.VARCHAR) .build(); ShardingKey shardingKey = ds.createShardingKeyBuilder() .subkey("PITTSBURGH_BRANCH", JDBCType.VARCHAR) .build(); Connection con = ds.createConnectionBuilder() .user("rafa") .password("tennis") .shardingKey(shardingKey) .superShardingKey(superShardingKey) .build(); ``` -------------------------------- ### Start jstatd with External RMI Registry Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jstatd Starts a jstatd session that connects to an external RMI registry. This is the basic setup for monitoring Java processes via RMI. ```shell rmiregistry& jstatd ``` -------------------------------- ### Example: List Default Keytable Entries Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/ktab Demonstrates how to list all entries in the default keytable using the `-l` option. ```shell ktab -l ``` -------------------------------- ### Get Start Point Methods (Point2D) Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/java/awt/geom/class-use/Point2D Retrieves the starting point of various geometric shapes as a Point2D object. These methods are common across different implementations of lines and curves. ```APIDOC Line2D.Float.getP1() Returns the start Point2D of this Line2D. Line2D.getP1() Returns the start Point2D of this Line2D. QuadCurve2D.Double.getP1() Returns the start point. QuadCurve2D.Float.getP1() Returns the start point. QuadCurve2D.getP1() Returns the start point. Arc2D.getStartPoint() Returns the starting point of the arc. ``` -------------------------------- ### ToolProvider Interface API Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/spi/ToolProvider Documentation for the `ToolProvider` Java interface, which allows command-line tools to be invoked without starting a new VM. It defines methods for naming, describing, and running tools with arguments and output streams. ```APIDOC public interface ToolProvider An interface for command-line tools to provide a way to be invoked without necessarily starting a new VM. Tool providers are normally located using the service-provider loading facility defined by ServiceLoader. Each provider must provide a name, and a method to run an instance of the corresponding tool. When a tool is run, it will be provided with an array of string arguments, and a pair of streams: one for normal (or expected) output and the other for reporting any errors that may occur. The interpretation of the string arguments will normally be defined by each individual tool provider, but will generally correspond to the arguments that could be provided to the tool when invoking the tool from the command line. Since: 9 ``` ```APIDOC String name() Returns the name of this tool provider. API Note: It is recommended that the name be the same as would be used on the command line: for example, "javac", "jar", "jlink". Returns: the name of this tool provider ``` ```APIDOC Optional description() Returns a short description of the tool, or an empty Optional if no description is available. API Note: It is recommended that the description fits into a single line in order to allow creating concise overviews like the following: jar Create, manipulate, and extract an archive of classes and resources. javac Read Java declarations and compile them into class files. jlink Assemble a set of modules (...) into a custom runtime image. Implementation Requirements: This implementation returns an empty Optional. Returns: a short description of the tool, or an empty Optional if no description is available Since: 19 ``` ```APIDOC int run(PrintWriter out, PrintWriter err, String... args) Runs an instance of the tool, returning zero for a successful run. Any non-zero return value indicates a tool-specific error during the execution. Two streams should be provided, for "expected" output, and for any error messages. If it is not necessary to distinguish the output, the same stream may be used for both. API Note: The interpretation of the arguments will be specific to each tool. Parameters: out - a stream to which "expected" output should be written err - a stream to which any error messages should be written args - the command-line arguments for the tool Returns: the result of executing the tool. A return value of 0 means the tool did not encounter any errors; any other value indicates that at least one error occurred during execution. ``` ```APIDOC default int run(PrintStream out, PrintStream err, String... args) Runs an instance of the tool, returning zero for a successful run. Parameters: out - a stream to which "expected" output should be written err - a stream to which any error messages should be written args - the command-line arguments for the tool Returns: the result of executing the tool. ``` ```APIDOC static Optional findFirst(String name) Returns the first instance of a ToolProvider with the given name, as loaded by ServiceLoader using the system class loader. Parameters: name - the name of the tool provider to find Returns: an Optional describing the first ToolProvider with the given name, or an empty Optional if no such tool provider is found. ``` -------------------------------- ### HttpServerProvider Class and Methods Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.httpserver/com/sun/net/httpserver/spi/HttpServerProvider Documentation for the HttpServerProvider abstract class, including its protected constructor and abstract methods for creating HttpServer and HttpsServer instances. It also details the static method to retrieve the default provider. ```APIDOC Class: com.sun.net.httpserver.spi.HttpServerProvider Service provider class for HttpServer. Sub-classes of HttpServerProvider provide an implementation of HttpServer and associated classes. Applications do not normally use this class. See provider() for how providers are found and loaded. Constructor Summary: protected HttpServerProvider() Initializes a new instance of this class. Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("httpServerProvider") Method Summary: abstract HttpServer createHttpServer(InetSocketAddress addr, int backlog) Creates a HttpServer from this provider. Parameters: addr: The address to bind to. May be null. backlog: The socket backlog. A value of zero means the system's default. Returns: An instance of HttpServer. Throws: IOException - if an I/O error occurs. abstract HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) Creates a HttpsServer from this provider. Parameters: addr: The address to bind to. May be null. backlog: The socket backlog. A value of zero means the system's default. Returns: An instance of HttpServer. Throws: IOException - if an I/O error occurs. static HttpServerProvider provider() Returns the system wide default HttpServerProvider for this invocation of the Java virtual machine. ``` -------------------------------- ### DocSourcePositions API Methods Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.compiler/com/sun/source/util/DocSourcePositions Provides methods to get the start and end character positions of DocTree elements within a Javadoc comment in a compilation unit. Positions are character offsets from the start of the CompilationUnit. ```APIDOC DocSourcePositions Interface Provides methods to obtain the position of a DocTree within a javadoc comment. A position is defined as a simple character offset from the start of a CompilationUnit where the first character is at offset 0. Methods: getStartPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) Description: Returns the starting position of the tree within the comment within the file. Parameters: file (CompilationUnitTree): The compilation unit in which to find the tree. comment (DocCommentTree): The comment tree that encloses the tree for which the position is being sought. tree (DocTree): The tree for which a position is sought. Returns: The start position of the tree as a long. Returns Diagnostic.NOPOS if the tree is not found or the position is unavailable. Constraints: - The given tree should be under the given comment tree. - The returned position must be at the start of the yield of this tree. - For any sub-tree of this tree, the following must hold: getStartPosition(file, comment, tree) <= getStartPosition(file, comment, subtree) or getStartPosition(file, comment, tree) == NOPOS or getStartPosition(file, comment, subtree) == NOPOS getEndPosition(CompilationUnitTree file, DocCommentTree comment, DocTree tree) Description: Returns the ending position of the tree within the comment within the file. Parameters: file (CompilationUnitTree): The compilation unit in which to find the tree. comment (DocCommentTree): The comment tree that encloses the tree for which the position is being sought. tree (DocTree): The tree for which a position is sought. Returns: The end position of the tree as a long. Returns Diagnostic.NOPOS if the tree is not found or the position is unavailable. Constraints: - The given tree should be under the given comment tree. - The returned position must be at the end of the yield of this tree. - For any sub-tree of this tree, the following must hold: getEndPosition(file, comment, tree) >= getEndPosition(file, comment, subtree) or getEndPosition(file, comment, tree) == NOPOS or getEndPosition(file, comment, subtree) == NOPOS - The following must hold: getStartPosition(file, comment, tree) <= getEndPosition(file, comment, tree) or getStartPosition(file, comment, tree) == NOPOS or getEndPosition(file, comment, tree) == NOPOS Inherited from SourcePositions: getEndPosition(CompilationUnitTree, Tree) getStartPosition(CompilationUnitTree, Tree) ``` -------------------------------- ### Example GET Request with Async Response Handling Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.net.http/java/net/http/HttpRequest Demonstrates creating an HttpRequest, sending it asynchronously using HttpClient, and processing the String response body. This example uses the newHttpClient and BodyHandlers classes. ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://foo.com/")) .build(); client.sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join(); ``` -------------------------------- ### Example: Using a Single Argument File Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/java Shows the basic usage of the java command with a single argument file containing all necessary arguments. ```shell java @myargumentfile ``` -------------------------------- ### Java Debug Interface (JDI) Connector Management and Launching Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.jdi/com/sun/jdi/VirtualMachineManager Comprehensive documentation for JDI connector management, VM launching, and debugger attachment. This covers the core interfaces and processes involved in setting up a debugging session. ```APIDOC Java Debug Interface (JDI) Connector Management and Launching: **VM Launching with Debugger (JDWP)** * **Purpose**: To launch a target VM with the Java Debug Wire Protocol (JDWP) agent enabled, allowing a debugger to connect. * **Mechanism**: The target VM is launched with specific JVM arguments, typically including `-agentlib:jdwp=...`. * **Example Argument**: `-agentlib:jdwp=launch=cmdline,onuncaught=y,transport=xxx,server=y` * `launch=cmdline`: Indicates the VM should launch the debugger. * `onuncaught=y`: Triggers debugger connection on uncaught exceptions. * `transport=xxx`: Specifies the transport mechanism (e.g., 'dt_socket'). * `server=y`: Indicates the VM will listen for debugger connections. * **Process**: The VM generates a transport-specific address, and the debugger uses this address to attach. **Connector Discovery and Management** * **`VirtualMachineManager`**: The central point for managing JDI Connectors. * **`Bootstrap.virtualMachineManager()`**: Retrieves the `VirtualMachineManager` instance. Connectors are created when this method is first invoked. * **`allConnectors()`**: Returns a list of all Connectors created at startup. * **`Connector` Interface**: Represents a mechanism for establishing a connection to a target VM. * **Subtypes**: `AttachingConnector`, `ListeningConnector`, `LaunchingConnector`. * **Installation**: Connectors are installed via jar files containing a provider configuration file (`META-INF/services/Connector`) listing the fully-qualified class names of Connector implementations. * **Provider Configuration File Format**: UTF-8 encoded, one fully-qualified class name per line. Whitespace and comments (`#`) are ignored. * **`TransportService`**: Encapsulates transport-specific implementations. * **Installation**: Similar to Connectors, via `META-INF/services/TransportService`. * **VM Creation**: `VirtualMachineManager` creates `AttachingConnector` instances to encapsulate installed `TransportService` implementations. **Debugger Attachment Process** * **Connector Selection**: The debugger selects a connector matching the transport name (e.g., from `attachingConnectors()`). * **Argument Configuration**: Debugger modifies connector default arguments (obtained via `Connector.defaultArguments()`) to specify the target VM's listening address. * **Attachment**: The debugger calls `AttachingConnector.attach(java.util.Map)` to establish the connection. * **Result**: Returns a `VirtualMachine` mirror representing the connected VM. **Related Methods/Interfaces**: * `Connector.defaultArguments()`: Retrieves default arguments for a connector. * `AttachingConnector.attach(java.util.Map)`: Attaches to a target VM. * `VirtualMachine`: Represents the connected target VM. * `attachingConnectors()`: Gets available attaching connectors. * `Connector`: Base interface for all connectors. * `AttachingConnector`: Interface for connectors that attach to a running VM. * `ListeningConnector`: Interface for connectors that listen for incoming VM connections. * `LaunchingConnector`: Interface for connectors that launch a VM and attach to it. * `TransportService`: Interface for transport implementations. ``` -------------------------------- ### Compact Number Pattern Array Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/text/CompactNumberFormat An example array of compact number patterns for the SHORT style and US locale, ranging from 10^0 to 10^14. Patterns are index-based, starting from 10^0. ```Java String[] compactPatterns = {"", "", "", "0K", "00K", "000K", "0M", "00M", "000M", "0B", "00B", "000B", "0T", "00T", "000T"}; ``` -------------------------------- ### SimpleFileServer API Documentation Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.httpserver/com/sun/net/httpserver/SimpleFileServer API reference for SimpleFileServer static factory methods used to create HTTP file server components. Includes details on creating the server, file handler, and output filter. ```APIDOC Class: com.sun.net.httpserver.SimpleFileServer Description: A simple HTTP file server and its components (intended for testing, development and debugging purposes only). Static Factory Methods: 1. createFileServer(InetSocketAddress addr, Path baseDirectory, SimpleFileServer.OutputLevel outputLevel) - Returns an HttpServer that is a simple out-of-the-box file server. - Serves files from the given directory path and its subdirectories. - outputLevel determines what log messages are printed to System.out. - Parameters: - addr: The InetSocketAddress to bind the server to. - baseDirectory: The Path to the directory from which files will be served. - outputLevel: The level of logging detail (e.g., INFO, VERBOSE). - Example: var addr = new InetSocketAddress(8080); var server = SimpleFileServer.createFileServer(addr, Path.of("/some/path"), OutputLevel.INFO); server.start(); 2. createFileHandler(Path baseDirectory) - Returns an HttpHandler that serves files and directory listings. - Supports only HEAD and GET request methods. - Parameters: - baseDirectory: The Path to the directory from which files will be served. - Usage: Can be composed with other handlers using HttpHandlers.handleOrElse. Example: var handler = HttpHandlers.handleOrElse( (req) -> req.getRequestMethod().equals("PUT"), (exchange) -> { /* handle PUT */ }, SimpleFileServer.createFileHandler(Path.of("/some/path")) ); 3. createOutputFilter(OutputStream out, SimpleFileServer.OutputLevel outputLevel) - Returns a post-processing filter that prints log messages relating to server exchanges. - The output format is specified by the outputLevel. - Parameters: - out: The OutputStream to which log messages are written. - outputLevel: The level of logging detail. - Example: var filter = SimpleFileServer.createOutputFilter(System.out, OutputLevel.VERBOSE); var server = HttpServer.create(new InetSocketAddress(8080), 10, "/some/path/", new SomeHandler(), filter); server.start(); Related Classes: - HttpServer - HttpHandler - Filter - HttpHandlers ``` -------------------------------- ### UI Installation and Listener Management Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/plaf/basic/BasicProgressBarUI Manages the installation and uninstallation of default properties and listeners for the progress bar UI delegate. Includes methods inherited from ComponentUI for UI setup and teardown. ```APIDOC installDefaults() Installs default properties. uninstallDefaults() Uninstalls default properties. installListeners() Registers listeners. uninstallListeners() Removes all listeners installed by this object. installUI(JComponent c) Invoked by the "add" method of the component to install the UI delegate. uninstallUI(JComponent c) Invoked by the "remove" method of the component to uninstall the UI delegate. ``` -------------------------------- ### Example: Signing a JAR File with jarsigner Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jarsigner Demonstrates the basic command to sign a JAR file. This example shows how to specify the JAR file and the alias for the digital signature. ```bash jarsigner myapp.jar myalias ``` -------------------------------- ### Get Text Start Offset - Java XML Stream API Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.xml/javax/xml/stream/XMLStreamReader Retrieves the starting offset of text content within the character array for the current text event. Throws IllegalStateException if the current state is invalid. ```APIDOC getTextStart() int getTextStart() Returns the offset into the text character array where the first character (of this text event) is stored. Returns: the starting position of the text in the character array Throws: IllegalStateException - if this state is not a valid text state. ``` -------------------------------- ### JarSigner Usage Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.jartool/jdk/security/jarsigner/JarSigner Demonstrates how to create a JarSigner instance using its Builder, configure digest and signature algorithms, and then use the signer to sign a JAR file. ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.ZipFile; import jdk.security.jarsigner.JarSigner; public class JarSignerExample { public static void main(String[] args) { // Assuming key and certPath are defined and valid // Key key = ...; // String certPath = "path/to/certificate.pfx"; // String inputFile = "path/to/input.jar"; // String outputFile = "path/to/output.jar"; /* try { JarSigner signer = new JarSigner.Builder(key, certPath) .digestAlgorithm("SHA-256") .signatureAlgorithm("SHA256withRSA") .build(); try (ZipFile in = new ZipFile(inputFile); FileOutputStream out = new FileOutputStream(outputFile)) { signer.sign(in, out); } } catch (IOException | JarSignerException e) { e.printStackTrace(); } */ } } ``` -------------------------------- ### Java Calendar Date Calculation Example Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/keytool Demonstrates how to calculate a certificate start date using `java.util.GregorianCalendar.add` method. This example shows how to shift the current date by specified units of years, months, days, hours, minutes, or seconds. ```Java import java.util.Calendar; import java.util.GregorianCalendar; // ... inside a method or class Calendar c = new GregorianCalendar(); c.add(Calendar.YEAR, -1); c.add(Calendar.MONTH, 1); c.add(Calendar.DATE, -1); // The 'c' Calendar object now holds the calculated date and time. ``` -------------------------------- ### jmod Create Example Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jmod Demonstrates how to create a JMOD file using the `jmod create` command with various options, including specifying class paths, native commands, configuration files, and module details. ```APIDOC jmod create --class-path mods/com.greetings --cmds commands --config configfiles --header-files src/h --libs lib --main-class com.greetings.Main --man-pages man --module-version 1.0 --os-arch "x86_x64" --os-name "macOS" --os-version "10.10.5" greetingsmod ``` -------------------------------- ### Get Target Line Info Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/sound/sampled/AudioSystem Obtains information about all target lines of a particular type supported by the installed mixers. ```APIDOC Line.Info[] getTargetLineInfo(Line.Info info) Obtains information about all target lines of a particular type that are supported by the installed mixers. ``` -------------------------------- ### Example: Verification with Certificate Information Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jarsigner Shows how to verify a signed JAR file and display detailed certificate information for each signature. This is useful for inspecting the trust chain and validity of the signer's certificate. ```bash jarsigner -verify -certs myapp.jar ``` -------------------------------- ### Get Source Line Info Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/sound/sampled/AudioSystem Obtains information about all source lines of a particular type supported by the installed mixers. ```APIDOC Line.Info[] getSourceLineInfo(Line.Info info) Obtains information about all source lines of a particular type that are supported by the installed mixers. ``` -------------------------------- ### Start EventStream Asynchronously Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.jfr/jdk/jfr/consumer/RecordingStream Starts asynchronous processing of actions in a single separate thread. To stop the stream, use the close() method. The example demonstrates enabling CPU load events and printing them for ten seconds. ```Java try (var stream = new RecordingStream()) { stream.enable("jdk.CPULoad").withPeriod(Duration.ofSeconds(1)); stream.onEvent("jdk.CPULoad", event -> { System.out.println(event); }); stream.startAsync(); Thread.sleep(10_000); } ``` -------------------------------- ### Virtual Machine and Attach Provider APIs Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/class-use/List APIs for listing and interacting with Java Virtual Machines and attach providers. Includes methods to list running VMs and available attach providers. ```APIDOC VirtualMachine.list() Return a list of Java virtual machines. AttachProvider.listVirtualMachines() Lists the Java virtual machines known to this provider. AttachProvider.providers() Returns a list of the installed attach providers. ``` -------------------------------- ### Help and Version Information Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/java Options to display help messages and product version information to the console. ```APIDOC `-help`, `-h`, or `-?` Prints the help message to the error stream. `--help` Prints the help message to the output stream. `--show-version` Prints the product version to the output stream and continues execution. `-showversion` Prints the product version to the error stream and continues execution. ``` -------------------------------- ### ByteBuffer Absolute Bulk Get Operations Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/nio/ByteBuffer Documents absolute bulk get methods for Java's ByteBuffer. These methods transfer bytes from the buffer into a destination array starting at a specified index. They are efficient and perform parameter consistency checks. ```APIDOC ByteBuffer.get(int index, byte[] dst, int offset, int length) Absolute bulk *get* method. Transfers `length` bytes from this buffer into the given array, starting at the given index in this buffer and at the given offset in the array. The position of this buffer is unchanged. Parameters: - index: The index in this buffer from which the first byte will be read; must be non-negative and less than `limit()` - dst: The destination array - offset: The offset within the array of the first byte to be written; must be non-negative and less than `dst.length` - length: The number of bytes to be written to the given array; must be non-negative and no larger than the smaller of `limit() - index` and `dst.length - offset` Returns: This buffer Throws: - IndexOutOfBoundsException: If the preconditions on the `index`, `offset`, and `length` parameters do not hold Since: 13 ByteBuffer.get(int index, byte[] dst) Absolute bulk *get* method. Transfers bytes from this buffer into the given destination array. The position of this buffer is unchanged. This is equivalent to `src.get(index, dst, 0, dst.length)`. Parameters: - index: The index in this buffer from which the first byte will be read; must be non-negative and less than `limit()` - dst: The destination array Returns: This buffer Throws: - IndexOutOfBoundsException: If `index` is negative, not smaller than `limit()`, or `limit() - index < dst.length` Since: 13 ByteBuffer.get(byte[] a) Relative bulk *get* method. Transfers bytes from this buffer into the given destination array. The position of this buffer is unchanged. This is equivalent to `src.get(a, 0, a.length)`. Parameters: - a: The destination array Returns: This buffer Throws: - BufferUnderflowException: If there are fewer than `length` bytes remaining in this buffer ``` -------------------------------- ### HttpServer.create Method (Java HTTP Server) Source: https://docs.oracle.com/en/java/javase/21/docs/api/new-list Creates an `HttpServer` instance with an initial context. This method is part of the com.sun.net.httpserver package. ```APIDOC com.sun.net.httpserver.HttpServer.create(java.net.InetSocketAddress address, int backlog, String contextPath, com.sun.net.httpserver.HttpHandler handler, com.sun.net.httpserver.Filter... filters) Creates an `HttpServer` instance with an initial context. ``` -------------------------------- ### EventStream onMetadata Method with Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.jfr/jdk/jfr/consumer/EventStream Registers an action to perform when new metadata arrives in the stream. The event type of an event always arrives sometime before the actual event. The action must be registered before the stream is started. Provides an example of filtering and processing event types. ```APIDOC default void onMetadata(Consumer action) Registers an action to perform when new metadata arrives in the stream. The event type of an event always arrives sometime before the actual event. The action must be registered before the stream is started. The following example shows how to listen to new event types, register an action if the event type name matches a regular expression and increase a counter if a matching event is found. A benefit of using an action per event type, instead of the generic onEvent(Consumer) method, is that a stream implementation can avoid reading events that are of no interest. ```java static long count = 0; public static void main(String... args) throws IOException { Path file = Path.of(args[0]); String regExp = args[1]; var pr = Pattern.compile(regExp).asMatchPredicate(); try (var s = EventStream.openFile(file)) { s.setOrdered(false); s.onMetadata(metadata -> metadata.getAddedEventTypes() .stream().map(EventType::getName).filter(pr) .forEach(eventName -> s.onEvent(eventName, event -> count++))); s.start(); System.out.println(count + " events matches " + regExp); } } ``` Implementation Requirements: : The default implementation of this method is empty. Parameters: : action - to perform, not null Throws: : IllegalStateException - if an action is added after the stream has started Since: : 16 ``` -------------------------------- ### LinearGradientPaint Usage Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/java/awt/LinearGradientPaint Demonstrates the typical usage of `LinearGradientPaint` by creating an instance with specified start and end points, color distribution fractions, and colors. This example shows how to define a gradient that interpolates between red and white for the first 20% and white and blue for the remaining 80%. ```java import java.awt.geom.Point2D; import java.awt.Color; import java.awt.LinearGradientPaint; // ... Point2D start = new Point2D.Float(0, 0); Point2D end = new Point2D.Float(50, 50); float[] dist = {0.0f, 0.2f, 1.0f}; Color[] colors = {Color.RED, Color.WHITE, Color.BLUE}; LinearGradientPaint p = new LinearGradientPaint(start, end, dist, colors); ``` -------------------------------- ### Java Process Creation (`ProcessBuilder.start()`) Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Runtime Details the `ProcessBuilder.start()` method for creating new operating system processes. It covers parameters for command, environment, and working directory, along with potential exceptions like `IOException`, `SecurityException`, and `UnsupportedOperationException`. ```APIDOC ProcessBuilder.start() Parameters: cmdarray - array containing the command to call and its arguments. envp - array of strings, each element of which has environment variable settings in the format *name*=*value*, or null if the subprocess should inherit the environment of the current process. dir - the working directory of the subprocess, or null if the subprocess should inherit the working directory of the current process. Returns: A new Process object for managing the subprocess Throws: SecurityException - If a security manager exists and its checkExec method doesn't allow creation of the subprocess UnsupportedOperationException - If the operating system does not support the creation of processes. IOException - If an I/O error occurs NullPointerException - If cmdarray is null, or one of the elements of cmdarray is null, or one of the elements of envp is null IndexOutOfBoundsException - If cmdarray is an empty array (has length 0) Since: 1.3 See Also: ProcessBuilder ``` -------------------------------- ### Create and Start Basic HTTP Server in Java Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.httpserver/com/sun/net/httpserver/package-summary Demonstrates creating an HttpServer listening on a specific port, registering a custom HttpHandler for a URI path, and starting the server. It uses the calling application thread to invoke the handle() method for incoming HTTP requests. ```java class MyHandler implements HttpHandler { public void handle(HttpExchange t) throws IOException { InputStream is = t.getRequestBody(); read(is); // .. read the request body String response = "This is the response"; t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } } ... HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/applications/myapp", new MyHandler()); server.setExecutor(null); // creates a default executor server.start(); ``` -------------------------------- ### java.security.Policy Class Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/security/package-tree Represents the installed security policy. It provides a way to get the policy for a given CodeSource. ```java class java.security.Policy ``` -------------------------------- ### Creating and Starting Threads with Thread.Builder Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Thread Demonstrates the use of the `Thread.Builder` API in Java for creating and starting both platform and virtual threads. Examples include creating daemon threads, threads with custom names, unstarted threads, and thread factories for both types. ```java Runnable runnable = () -> System.out.println("Task executed"); // Start a daemon thread to run a task Thread thread = Thread.ofPlatform().daemon().start(runnable); // Create an unstarted thread with name "duke", its start() method // must be invoked to schedule it to execute. Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable); // A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ... ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory(); // Start a virtual thread to run a task Thread thread = Thread.ofVirtual().start(runnable); // A ThreadFactory that creates virtual threads ThreadFactory factory = Thread.ofVirtual().factory(); ``` -------------------------------- ### jwebserver Command Usage Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jwebserver Illustrates the general command-line syntax for the jwebserver tool. It shows how to invoke the server and specifies that options can be used to configure its behavior, such as binding address, port, and directory. ```bash jwebserver [-b bind address] [-p port] [-d directory] [-o none|info|verbose] [-h to show options] [-version to show version information] ``` -------------------------------- ### Javac Help Options (--help, -help, -?) Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/javac Displays a synopsis of the standard command-line options for the Javac compiler. ```APIDOC Javac Help Options: --help, -help, -? Prints a synopsis of the standard options. ``` -------------------------------- ### Get Target Formats Source: https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/sound/sampled/AudioSystem Obtains audio formats that match a target encoding and are obtainable from a given source format using installed converters. ```APIDOC AudioFormat[] getTargetFormats(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) Obtains the formats that have a particular encoding and that the system can obtain from a stream of the specified format using installed format converters. ``` -------------------------------- ### jwebserver Output Example Source: https://docs.oracle.com/en/java/javase/21/docs/specs/man/jwebserver Shows the typical output message displayed when the jwebserver starts successfully. It indicates the address and port the server is listening on, and the directory it is serving, along with the accessible URL. ```bash Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::". Serving /cwd and subdirectories on 127.0.0.1 port 8000 URL http://127.0.0.1:8000/ ``` -------------------------------- ### Basic Recording Lifecycle Example Source: https://docs.oracle.com/en/java/javase/21/docs/api/jdk.jfr/jdk/jfr/Recording Demonstrates how to configure, start, stop, and dump recording data to disk using the Recording class. ```java Configuration c = Configuration.getConfiguration("default"); try (Recording r = new Recording(c)) { r.start(); System.gc(); Thread.sleep(5000); r.stop(); r.dump(Files.createTempFile("my-recording", ".jfr")); } ```