Java Network Programming & Web Communication – Comprehensive Bullet Notes

Spam Check Functionality in Java

  • Purpose: Detect unsolicited/harmful messages (email, SMS, forum posts).
  • Core Techniques
    • Content analysis: scan body/subject/metadata for spam patterns (excessive links, "win money now", obfuscation like “fr33”).
    • Header inspection: verify sender, forged headers, spam-listed IPs.
    • Blacklist look-ups: compare sender IP/domain against RBLs.
    • Bayesian filtering: compute P(spamterms)P(\text{spam}|\text{terms}) using prior corpora.
    • Machine-learning / AI: train classifiers on thousands of labelled messages.
    • Pattern matching & heuristics: regex for repeated words, odd formatting.
    • Scoring & thresholds: aggregate rule scores; flag if total > cutoff.
  • Typical Deployments
    • Email providers (Gmail, Yahoo) – phishing & junk blocking.
    • Web forums/comment sections – prevent bot posts.
    • SMS gateways – block fraud texts.

Processing Server Log Files in Java

  • Pipeline
    • Collection: pull logs from web/app/db servers.
    • Parsing & tokenisation: split into fields (timestamp, IP, URL, status…).
    • Filtering & aggregation: group by severity (INFO/WARN/ERROR), detect bursts.
    • Pattern matching: regex for repeated 401/403, failed logins.
    • Real-time monitoring: stream logs for intrusion/failure alerts.
    • Storage & archiving: DB, flat-file, or cloud object store.
    • Reporting & visualisation: dashboards, time-series graphs.
  • Use-cases
    • Security monitoring (unauthorised logins, DDoS, malware).
    • Performance (slow queries, high CPU, bottlenecks).
    • Debugging (crash traces).
    • Compliance & auditing.

URL / URI Essentials

  • URL syntax: scheme://username:password@host:port/path?query#fragment
    • Base URI + Relative URI → base.resolve(relative)\text{base}.resolve(\text{relative}) to get absolute.
  • URI vs URL vs URN: URI = generic identifier; URL = locator; URN = name.
  • Components
    • Scheme (http, https, ftp…)
    • Authority (user, pass, host, port)
    • Path
    • Query string (key=value&…)
    • Fragment (#section)
  • Opaque URI: non-hierarchical; scheme-specific part treated as one chunk.

Spammers – Why Block Them

  1. Security (malware, phishing).
  2. Privacy (unsolicited data collection).
  3. Bandwidth & server costs.
  4. Reputation damage to domains/IPs.
  5. User-experience clutter.

x-www-form-urlencoded

  • Encodes POST body as query-string style: name=Rustam&age=25.
  • Java utilities: URLEncoder, URLDecoder, HttpClient’s FormBodyPublisher, etc.

Proxy Concepts

  • Types
    • Forward, Reverse, Transparent, Anonymous, Caching.
  • Use-cases: security isolation, privacy, caching, access-control.
  • Java flags
    • -Dhttp.proxyHost, -Dhttp.proxyPort, -Dhttp.nonProxyHosts="*.example.com|localhost".
  • java.net.Proxy / ProxySelector
    • Proxy.Type = HTTP, SOCKS, DIRECT.
    • ProxySelector.getDefault() pulls OS proxy; can override.
  • Authenticator & PasswordAuthentication
    • Central mechanism for Basic/Digest/proxy auth; credentials stored as char[].

HTTP Overview

  • Versions: 0.9 → 1.0 → 1.1 → 2 (binary, multiplexing) → 3 (QUIC).
  • Request line + headers + optional body; server returns status line + headers + body.
  • Common Methods: GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, TRACE.
  • Status Codes
    • 1xx Info (100,101)
    • 2xx Success (200,201,204)
    • 3xx Redirect (301,302,304)
    • 4xx Client (400,401,403,404)
    • 5xx Server (500,502,503)
  • Keep-Alive
    • Header: Connection: keep-alive, Keep-Alive: timeout=10, max=100.
    • Reuses single TCP connection → lower latency.

HTTP Request Body & Examples

  • POST (create), PUT (replace), PATCH (partial), DELETE.
  • JSON example shown with 201/200 responses.

Cookies & Java Handling

  • Cookie attributes: Expires, Max-Age, Domain, Path, Secure, HttpOnly, SameSite.
  • Risks: hijacking, XSS, CSRF.
  • Java classes
    • CookieHandler, CookieManager, CookieStore, custom overrides.

URLConnection / HttpURLConnection

  • Steps: new URL → openConnection → set headers/method → (write body) → read response → disconnect.
  • Features: multi-protocol (HTTP, HTTPS, FTP), input/output streams, auth, caching.
  • Comparison: URL = identifier; URLConnection = communication.

MIME Types

  • Define file formats (e.g., text/html, application/json, image/png).
  • Java: Files.probeContentType(path) guesses via extension or magic numbers.

Web Caching

  • Layers: browser, proxy, CDN, app cache.
  • Cache hit vs miss; improves load time, reduces bandwidth.
  • Java demo: ResponseCache.setDefault(...) — first call miss, second hit.
  • Security risks with stale/private data if mis-configured.

Security Risks with URLConnection & Mitigations

  1. Plain HTTP → sniffing. Use HTTPS.
  2. MITM → validate certs; set HSTS.
  3. Missing headers → add Authorization, Cache-Control: no-store.
  4. URL injection → validate trusted domain.
  5. Leaked API keys → never hardcode; encrypt.

Socket Communication Fundamentals

  • Why: IPC, client-server, real-time, remote control.
  • Properties
    • Address = IP+port.
    • TCP (reliable) vs UDP (fast, no guarantee).
    • Full-duplex; blocking/non-blocking modes.
  • Lifecycle (TCP): socket() → bind() → listen()/connect() → accept() → send/recv → close().
  • Advantages: speed, scalability, reliability (TCP).
  • Disadvantages: complexity, security exposure, overhead, network dependency.

Telnet for Testing

  • telnet host port → manually type HTTP GET / HTTP/1.1 to see raw response.

ServerSocket & Multithreaded Servers

  • ServerSocket(port) listens; each accept() returns new Socket.
  • Multithreaded: spawn ClientHandler thread per connection → concurrent service.
  • Exceptions: BindException, SocketException, IOException, SecurityException.
  • Binary data example: server sends timestamp as bytes, client decodes.

Socket Options Cheat-Sheet

  • TCP_NODELAY – disable Nagle, reduce latency.
  • SO_LINGER – control blocking close.
  • SO_TIMEOUT – read timeout.
  • SO_RCVBUF / SO_SNDBUF – buffer sizes.
  • SO_KEEPALIVE – periodic probes.
  • SO_REUSEADDR – quick rebinding.
  • SO_OOBINLINE – inline urgent data.
  • IP_TOS / setTrafficClass() – QoS bits.

Secure Sockets (SSL/TLS)

  • Package: javax.net.sslSSLSocket, SSLServerSocket, SSLContext.
  • Steps: load keystore → init context → create secure socket → handshake events via HandshakeCompletedListener.
  • Configure cipher suites (e.g., TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384).

Java Logging Basics

  • Purposes: debugging, performance, security audit, ops insight.
  • Levels (java.util.logging)
    • 10001000 SEVERE, 900900 WARNING, 800800 INFO, 700700 CONFIG, 500500 FINE, 400400 FINER, 300300 FINEST.
  • Avoid logging sensitive/PII data.

Java NIO (Non-blocking I/O)

  • Building blocks
    • Channels (SocketChannel, ServerSocketChannel, FileChannel, DatagramChannel).
    • Buffers (ByteBuffer, CharBuffer…) with capacity, limit, position, mark.
    • Selectors monitor many channels with one thread.
  • Workflow
    1. Channel non-blocking.
    2. Register with Selector for OP_READ/WRITE/ACCEPT/CONNECT.
    3. Loop selector.select() → iterate ready keys.
    4. Read/write via buffers; handle partial operations.
  • Buffer operations
    • put(), flip(), get(), clear(), compact(), duplicate(), slice().
  • Pros: high scalability, fewer threads.
  • Cons: complex callbacks, back-pressure handling, not always faster for small loads.

Selector / SelectionKey Quick Table

OperationMeaning
OP_ACCEPTServer socket ready to accept
OP_CONNECTClient ready to finish connect
OP_READData available to read
OP_WRITEChannel ready to write

UDP Programming in Java

  • Connectionless, no guarantee, max datagram 65,535 bytes65{,}535\ \text{bytes}.
  • Classes
    • DatagramSocket (send/recv) — send(packet), receive(packet), setSoTimeout().
    • DatagramPacket holds byte[], length, destination.
    • DatagramChannel (NIO, non-blocking) — send(ByteBuffer, addr), receive(ByteBuffer).
  • Socket options: SO_TIMEOUT, SO_RCVBUF, SO_SNDBUF, SO_REUSEADDR, SO_BROADCAST, IP_TOS.
  • Common echo server/client example; suitable for DNS, streaming, games.

IP Multicasting

  • Address range 224.0.0.0 – 239.255.255.255.
  • Routers use IGMP; protocols like PIM for routing.
  • Java MulticastSocketjoinGroup(addr) / leaveGroup(addr); send to group.
  • Use for live video, conferencing, distributed events.

Streaming Mode & Chunked Transfer in Java

  • setChunkedStreamingMode(1024) – send HTTP body in 1 KB chunks → low memory footprint.

WHOIS via Sockets

  • TCP port 43.
    Simple Java client connects to whois.verisign-grs.com, sends domain, prints registry info.

Summary Relationships & Implications

  • Effective spam/log processing + proxies + secure sockets ensure security and performance of Java network apps.
  • Understanding HTTP intricacies (methods, headers, keep-alive, status codes, cookies) is foundational for web APIs.
  • NIO & multithreaded servers offer scalable architectures; choose TCP vs UDP vs Multicast based on reliability vs speed.
  • Logging & MIME handling complement network code by adding observability and correct content negotiation.