<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chazool on Medium]]></title>
        <description><![CDATA[Stories by Chazool on Medium]]></description>
        <link>https://medium.com/@chazool?source=rss-3b8f227f5d9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*thKy_k2PkLJtprwD_Uo2EQ.jpeg</url>
            <title>Stories by Chazool on Medium</title>
            <link>https://medium.com/@chazool?source=rss-3b8f227f5d9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:19:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chazool/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Distributed Tracing in Rust using OpenTelemetry, OTEL Collector, and Jaeger]]></title>
            <link>https://chazool.medium.com/building-distributed-tracing-in-rust-using-opentelemetry-otel-collector-and-jaeger-289d6a134d7f?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/289d6a134d7f</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 15:23:17 GMT</pubDate>
            <atom:updated>2026-03-01T15:23:17.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yevz2S_8gbS5guRFYI01ZA.png" /></figure><p>Even a small API request usually travels through multiple layers:</p><pre><strong>Handler → Service → Repository → Database → External APIs</strong></pre><p>When something becomes slow or fails, developers usually ask:</p><ul><li>Where did the delay happen?</li><li>Which part of the system caused the error?</li><li>How long did each layer take?</li></ul><p>Logs alone rarely give a clear answer. Metrics show trends but not request flow.</p><p>This is where <strong>Distributed Tracing</strong> becomes extremely powerful.</p><p>In this article, we will build distributed tracing in a Rust service using:</p><ul><li><strong>OpenTelemetry (OTEL) : </strong>instrumentation standard</li><li><strong>OpenTelemetry Collector: </strong>telemetry pipeline</li><li><strong>Jaeger</strong> : trace visualization UI</li></ul><p>By the end, you will be able to see every request as a visual timeline similar to production observability platforms.</p><h4>Why Distributed Tracing Matters in Production</h4><p>Consider an API request taking <strong>900ms</strong>.</p><p>Without tracing:</p><pre><strong>The API is slow.</strong></pre><p>With tracing:</p><pre><strong>| Component      | Duration |<br>| -------------- | -------- |<br>| HTTP Handler   | 5ms      |<br>| Business Logic | 40ms     |<br>| Database Query | 820ms    |<br>| Serialization  | 35ms     |</strong></pre><p>Now the real problem becomes obvious. Distributed tracing turns debugging from guessing into observation.</p><h3>OpenTelemetry: The Observability Standard</h3><p>OpenTelemetry provides a unified way to generate telemetry:</p><ul><li><strong>Traces: </strong>request lifecycle</li><li><strong>Metrics: </strong>performance signals</li><li><strong>Logs: </strong>structured events</li></ul><p>The key architectural idea:</p><blockquote><em>Applications emit telemetry once using a standard protocol (OTLP).</em></blockquote><p>Where that data goes later becomes an infrastructure decision not an application rewrite.</p><p>This removes vendor lock in and enables long term observability evolution.</p><h3>Why the OpenTelemetry Collector Exists</h3><p>In production environments, applications typically do not send traces directly to a visualization backend such as Jaeger. Instead, an intermediate layer is introduced:</p><pre><strong>Rust Service → OTEL Collector → Observability Backend</strong></pre><p>The <strong>OpenTelemetry Collector</strong> acts as a centralized telemetry gateway between services and observability platforms. Applications export telemetry using the standard OTLP protocol, while the Collector is responsible for processing, routing, and delivering that data to one or more backends.</p><p>This architecture provides an important operational advantage:</p><blockquote><strong><em>Changing observability vendors becomes a configuration change rather than an application code change.</em></strong></blockquote><p>Additionally, the Collector enables capabilities such as batching, retry handling, sampling, filtering, and data enrichment all without modifying application logic making it a core component of production-grade observability systems.</p><h3>Step-by-Step: Create a Rust Distributed Tracing Project</h3><p>This section shows how to build the project from scratch in a clean and structured way.</p><h3>1. Create the Project</h3><p>Create a new Rust API project.</p><pre>cargo new rust-otel-collector<br>cd rust-otel-collector</pre><h3>2. Add Required Dependencies</h3><p>Open Cargo.toml and add:</p><pre>[dependencies]<br>tokio = { version = &quot;1&quot;, features = [&quot;macros&quot;,&quot;rt-multi-thread&quot;] }<br>axum = &quot;0.7&quot;<br>serde = { version = &quot;1&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1&quot;<br>uuid = { version = &quot;1&quot;, features = [&quot;v4&quot;] }<br><br># OpenTelemetry<br>opentelemetry = &quot;0.31&quot;<br>opentelemetry-otlp = { version = &quot;0.31&quot;, features = [&quot;grpc-tonic&quot;] }<br>opentelemetry_sdk = &quot;0.31&quot;<br><br># Tracing<br>tracing = { version = &quot;0.1&quot;, features = [&quot;attributes&quot;] }<br>tracing-opentelemetry = &quot;0.32&quot;<br>tracing-subscriber = { version = &quot;0.3&quot;, features = [&quot;fmt&quot;,&quot;json&quot;,&quot;registry&quot;] }</pre><ul><li>tracing : create spans in Rust</li><li>opentelemetry : export spans</li><li>otlp : send data to Collector</li></ul><h3>3. Configure OpenTelemetry</h3><h4>3.1 Resource and Tracer Provider</h4><p>A resource describes the service that produces telemetry, including metadata such as service name, version, and deployment environment. These attributes allow traces to be identified and grouped correctly across environments.</p><p>The tracer exports spans using OTLP (OpenTelemetry Protocol) to the OpenTelemetry Collector.</p><blockquote><em>Always use the full endpoint URI (for example </em><a href="http://otel-collector:4317)."><em>http://otel-collector:4317).</em></a><em> <br> Removing the scheme may cause gRPC transport errors because the tonic client expects a complete URI.</em></blockquote><pre>use crate::pkg::config::app_config;<br>use opentelemetry::KeyValue;<br>use opentelemetry_otlp::WithExportConfig;<br>use opentelemetry_sdk::{<br>    trace::{RandomIdGenerator, Sampler, SdkTracerProvider},<br>    Resource,<br>};<br>use opentelemetry_semantic_conventions::{<br>    attribute::{DEPLOYMENT_ENVIRONMENT_NAME, SERVICE_VERSION},<br>    SCHEMA_URL,<br>};<br><br>fn resource() -&gt; Resource {<br>    let config = app_config::get_config();<br><br>    Resource::builder()<br>        .with_service_name(config.service_name.clone())<br>        .with_schema_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20[%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20KeyValue::new(SERVICE_VERSION,%20config.service_version.clone()),<br>                KeyValue::new(DEPLOYMENT_ENVIRONMENT_NAME, config.environment.clone()),<br>            ],<br>            SCHEMA_URL,<br>        )<br>        .build()<br>}<br><br>pub fn init_tracer_provider(otel_endpoint: String) -&gt; SdkTracerProvider {<br>    let exporter = opentelemetry_otlp::SpanExporter::builder()<br>        .with_tonic()<br>        .with_endpoint(otel_endpoint)<br>        .build()<br>        .unwrap();<br><br>    SdkTracerProvider::builder()<br>        .with_sampler(Sampler::ParentBased(Box::new(<br>            Sampler::TraceIdRatioBased(1.0),<br>        )))<br>        .with_id_generator(RandomIdGenerator::default())<br>        .with_resource(resource())<br>        .with_batch_exporter(exporter)<br>        .build()<br>}</pre><h4>3.2 Subscriber and Guard</h4><p>Next, the tracer is connected to Rust’s tracing ecosystem using an OpenTelemetryLayer.</p><p>A guard object is introduced to ensure telemetry providers shut down cleanly when the application exits. Without this step, buffered spans may be lost during shutdown.</p><pre>use tracing_core::Level;<br>use tracing_opentelemetry::OpenTelemetryLayer;<br>use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};<br><br>pub struct OtelGuard {<br>    pub tracer_provider: SdkTracerProvider,<br>    pub meter_provider: SdkMeterProvider,<br>}<br><br>impl Drop for OtelGuard {<br>    fn drop(&amp;mut self) {<br>        if let Err(e) = self.tracer_provider.shutdown() {<br>            tracing::error!(&quot;Error shutting down tracer provider: {}&quot;, e);<br>        }<br><br>        if let Err(e) = self.meter_provider.shutdown() {<br>            tracing::error!(&quot;Error shutting down meter provider: {}&quot;, e);<br>        }<br>    }<br>}<br><br>pub fn init_tracing_subscriber() -&gt; OtelGuard {<br>    let config = app_config::get_config();<br><br>    let tracer_provider = init_tracer_provider(config.otel_endpoint.clone());<br>    let meter_provider = init_meter_provider();<br><br>    let tracer = tracer_provider.tracer(&quot;&quot;);<br><br>    tracing_subscriber::registry()<br>        .with(tracing_subscriber::filter::LevelFilter::from_level(Level::INFO))<br>        .with(<br>            tracing_subscriber::fmt::layer()<br>                .json()<br>                .with_target(true)<br>                .with_thread_ids(true)<br>                .with_thread_names(true)<br>                .with_file(true)<br>                .with_line_number(true)<br>                .with_current_span(true)<br>                .with_span_list(true),<br>        )<br>        .with(OpenTelemetryLayer::new(tracer))<br>        .init();<br><br>    OtelGuard {<br>        tracer_provider,<br>        meter_provider,<br>    }<br>}</pre><p>The project also defines init_meter_provider() for metrics export.<br> If only tracing is required, metrics initialization can be omitted.</p><h4>3.3 Bootstrap in main.rs</h4><p>Tracing must be initialized early and remain active for the lifetime of the process.</p><pre>use rust_otel_collector::{app::route, pkg::web};<br>use rust_otel_collector::pkg::tracing::tracing as custom_tracing;<br><br>#[tokio::main]<br>async fn main() {<br>    tracing::info!(&quot;service starting...&quot;);<br><br>    rust_otel_collector::pkg::config::app_config::init_app_config();<br><br>    // Guard must live for the entire application lifetime<br>    let _guard = custom_tracing::init_tracing_subscriber();<br><br>    let app = route::get_routes();<br>    web::init_web(app).await;<br><br>    tracing::info!(&quot;service stopping...&quot;);<br>}</pre><h3>4. Parent and Child Spans</h3><p>To visualize execution flow clearly, each architectural layer is instrumented using tracing::instrument.</p><p>Span context automatically propagates across async .await boundaries, allowing child spans to attach to their parent without manual handling.</p><p>The handler span becomes the trace root:</p><pre><strong>handler → service → repository</strong></pre><p><strong>Using </strong><strong>skip in </strong><strong>#[instrument]</strong></p><p>By default, all function parameters are recorded as span attributes.</p><p>Use skip(...) to avoid recording unnecessary or sensitive data:</p><ul><li>skip(state) avoids logging application state</li><li>skip(body)prevents recording request payloads</li><li>skip(self)avoids serializing repository structures</li></ul><p>Do <strong>not</strong> skip request_id it is required for request correlation.</p><h4>4.1 Handler (Root Span)</h4><pre>#[instrument(skip(state), name = &quot;handler.list_products&quot;)]<br>pub async fn list_products(<br>    request_id: RequestId,<br>    State(state): State&lt;AppState&gt;,<br>) -&gt; impl IntoResponse {<br>    let products = product_service::list_products(&amp;state).await;<br>    (StatusCode::OK, Json(products))<br>}</pre><h4>4.2 Service Layer</h4><pre>#[instrument(skip(state), name = &quot;product_service.list_products&quot;)]<br>pub async fn list_products(state: &amp;AppState) -&gt; Vec&lt;ProductResponse&gt; {<br>    state.product_repo.get_all().await<br>}</pre><h4>4.3 Repository Layer</h4><pre>#[instrument(skip(self), name = &quot;product_repo.get_all&quot;)]<br>pub async fn get_all(&amp;self) -&gt; Vec&lt;ProductResponse&gt; {<br>    self.store.read().await.values().cloned().collect()<br>}</pre><p>Each request produces a single trace tree representing the execution path through the system.</p><h3>5. Request ID : Correlating Logs and Traces</h3><p>Each request is assigned a unique X-Request-Id.</p><p>The middleware:</p><ul><li>extracts or generates a UUID</li><li>stores it in request extensions</li><li>adds it to the response header</li><li>logs request lifecycle events</li></ul><pre>use axum::{<br>    extract::{FromRequestParts, Request},<br>    http::{header::HeaderName, HeaderValue, request::Parts, StatusCode},<br>    middleware::Next,<br>    response::Response,<br>};<br>use uuid::Uuid;<br><br>pub const REQUEST_ID_HEADER: &amp;str = &quot;x-request-id&quot;;<br><br>/// Stored in request extensions; use as extractor so #[instrument] records it on the span.<br>#[derive(Clone, Copy, Debug)]<br>pub struct RequestId(pub Uuid);<br><br>impl std::fmt::Display for RequestId {<br>    fn fmt(&amp;self, f: &amp;mut std::fmt::Formatter&lt;&#39;_&gt;) -&gt; std::fmt::Result {<br>        self.0.fmt(f)<br>    }<br>}<br><br>impl&lt;S&gt; FromRequestParts&lt;S&gt; for RequestId<br>where<br>    S: Send + Sync,<br>{<br>    type Rejection = (StatusCode, &amp;&#39;static str);<br><br>    async fn from_request_parts(parts: &amp;mut Parts, _state: &amp;S) -&gt; Result&lt;Self, Self::Rejection&gt; {<br>        parts<br>            .extensions<br>            .get::&lt;RequestId&gt;()<br>            .copied()<br>            .ok_or((StatusCode::INTERNAL_SERVER_ERROR, &quot;missing request_id&quot;))<br>    }<br>}<br><br>pub async fn request_id_middleware(mut request: Request, next: Next) -&gt; Response {<br>    let request_id = extract_or_generate_request_id(&amp;request);<br>    let method = request.method().to_string();<br>    let path = request.uri().path().to_string();<br><br>    request.extensions_mut().insert(RequestId(request_id));<br><br>    tracing::info!(<br>        request_id = %request_id,<br>        method = %method,<br>        path = %path,<br>        &quot;request started&quot;<br>    );<br><br>    let mut response = next.run(request).await;<br><br>    if let Ok(value) = HeaderValue::try_from(request_id.to_string()) {<br>        response<br>            .headers_mut()<br>            .insert(HeaderName::from_static(REQUEST_ID_HEADER), value);<br>    }<br><br>    let status = response.status();<br>    tracing::info!(<br>        request_id = %request_id,<br>        status = %status,<br>        &quot;request completed&quot;<br>    );<br><br>    response<br>}<br><br>fn extract_or_generate_request_id&lt;B&gt;(request: &amp;Request&lt;B&gt;) -&gt; Uuid {<br>    request<br>        .headers()<br>        .get(REQUEST_ID_HEADER)<br>        .and_then(|v| v.to_str().ok())<br>        .and_then(|s| Uuid::parse_str(s).ok())<br>        .unwrap_or_else(Uuid::new_v4)<br>}</pre><p>The middleware intentionally does not create a root span.<br> Instead, the handler span remains the root, keeping trace naming consistent.</p><p>Because RequestId is included as a handler parameter and not skipped, it becomes a span attribute. This allows logs and traces to be correlated using the same identifier.</p><h3>6. Docker Compose: App + OTEL Collector + Trace Backend</h3><h4>6.1 docker-compose.yml</h4><p>Key points (important)</p><ul><li><strong>App &gt;&gt; Collector</strong></li></ul><p>App exports telemetry using: Always keep the full URI with <a href="http://./">http://.</a></p><pre>OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317</pre><ul><li><strong>Collector ports : </strong>We map collector gRPC port to <strong>14317</strong> on host to avoid conflicts:</li></ul><pre>container: 4317<br>host: 14317</pre><p>So your app container uses otel-collector:4317, but your local machine can access collector via localhost:14317.</p><pre>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: rust-otel-collector-app<br>    environment:<br>      PORT: &quot;8080&quot;<br>      OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317<br>      OTEL_ENDPOINT: http://otel-collector:4317<br>      SERVICE_NAME: rust-otel-collector<br>      SERVICE_VERSION: &quot;0.1.0&quot;<br>      ENVIRONMENT: development<br>    ports:<br>      - &quot;8080:8080&quot;<br>    depends_on:<br>      - otel-collector<br>    networks:<br>      - rust-otel-network<br>    restart: unless-stopped<br><br>  otel-collector:<br>    image: otel/opentelemetry-collector-contrib:latest<br>    command: [&quot;--config=/etc/otel-collector-config.yaml&quot;]<br>    volumes:<br>      - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml<br>    ports:<br>      - &quot;14317:4317&quot;  # OTLP gRPC (host 14317 to avoid conflict with host 4317)<br>      - &quot;14318:4318&quot;  # OTLP HTTP<br>      - &quot;9090:9090&quot;   # Prometheus metrics<br>    depends_on:<br>      - jaeger<br>    networks:<br>      - rust-otel-network<br><br>  jaeger:<br>    image: jaegertracing/all-in-one:latest<br>    ports:<br>      - &quot;6831:6831/udp&quot;   # Jaeger agent<br>      - &quot;16686:16686&quot;     # Jaeger Web UI<br>      - &quot;14268:14268&quot;     # HTTP collector<br>      - &quot;4317:4317&quot;       # OTLP gRPC (all-in-one supports OTLP)<br>    networks:<br>      - rust-otel-network<br><br>networks:<br>  rust-otel-network:<br>    driver: bridge</pre><h4>6.2 OpenTelemetry Collector Configuration (otel-collector-config.yaml)</h4><p>The OpenTelemetry Collector is configured using a YAML file.<br> This configuration defines how telemetry data is received, how it is processed, and where it is exported.</p><pre>receivers:<br>  otlp:<br>    protocols:<br>      grpc:<br>        endpoint: 0.0.0.0:4317<br>      http:<br>        endpoint: 0.0.0.0:4318<br><br>processors:<br><br>extensions:<br>  health_check: {}<br><br>exporters:<br>  otlp:<br>    endpoint: jaeger:4317<br>    tls:<br>      insecure: true<br>  prometheus:<br>    endpoint: &quot;0.0.0.0:9090&quot;<br><br>service:<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      exporters: [otlp]<br>    metrics:<br>      receivers: [otlp]<br>      exporters: [prometheus]</pre><h3>7. Running the stack</h3><p>Start all services:</p><pre>docker compose up -d --build</pre><p>Open the trace UI:</p><pre>http://localhost:16686</pre><p>Select your service name (rust-otel-collector) and click <strong>Find Traces</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pblbkta3BlOofSDWSuGLBw.png" /><figcaption>Jaeger Search View</figcaption></figure><p>Each API request creates a single trace containing multiple spans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GGJv3uWDzNaxe0Ls324cA.png" /><figcaption>Trace Detail View</figcaption></figure><p>Request Correlation in Jaeger, Because we include request_id in spans, it appears as a trace attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2AiPh2u-rEAKjsugzBT2Q.png" /><figcaption>Span Attributes Panel</figcaption></figure><h3>Conclusion</h3><p>Distributed tracing helps us understand what truly happens inside a request.</p><p>Instead of guessing where problems occur, we can clearly see how a request moves through each layer of the system and how much time is spent at every step. This makes identifying performance bottlenecks and failures much easier.</p><p>In this article, we built a complete tracing setup using Rust and OpenTelemetry. The application generates spans, the OpenTelemetry Collector manages the telemetry flow, and the tracing backend visualizes the request execution path. This architecture keeps the application independent from any specific observability vendor while allowing the system to scale as requirements grow.</p><p>The key idea is simple:</p><blockquote><strong><em>The application focuses on producing telemetry, while the collector decides where that telemetry goes.</em></strong></blockquote><p>Once tracing is in place, adding metrics and structured logging becomes a natural next step toward full observability.</p><p>You now have a production-ready foundation that can be extended with sampling strategies, multiple services, or additional telemetry backends.</p><p>For further reference and to explore the full implementation, you can find the repository <a href="https://github.com/chazool/rust-otel-collector">here</a>.</p><p>— Happy coding! 💻😊 —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=289d6a134d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Deploying GCP Cloud Pub/Sub trigger Function with Reusable Golang Code]]></title>
            <link>https://chazool.medium.com/building-and-deploying-gcp-cloud-pub-sub-trigger-function-with-reusable-golang-code-1418c860a7d8?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1418c860a7d8</guid>
            <category><![CDATA[production]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Fri, 31 May 2024 07:54:37 GMT</pubDate>
            <atom:updated>2024-05-31T10:36:42.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*2sfoli2ORk-x6HjUoHodkg.png" /></figure><p>Google Cloud Functions offer a serverless platform to build and deploy event-driven applications. Leveraging GoLang for this purpose can be efficient due to its concurrency support and performance. In this guide, we’ll walk through the process of building and deploying GCP Cloud Functions using reusable GoLang code.</p><h3><strong>Setup Environment</strong></h3><p>Ensure you have the Google Cloud SDK installed and authenticated. Install the Go programming language and set up your development environment. Also, make sure you have Go Modules enabled for dependency management.</p><h3>Directory Structure</h3><pre>PUBSUB_CLOUD_FUNC<br>└── app<br>    ├── dto<br>    │   └── item.go<br>    ├── repository<br>    │   └── item_repo.go<br>    ├── service<br>    │   └── item_service.go<br>└── cloud_func<br>    └── new_item<br>        ├── go.mod<br>        ├── go.sum<br>        ├── key.json<br>        └── new_item.go<br>└── pkg<br>    └── util.go<br>└── go.mod</pre><h3>Implement reusable code</h3><p>First, let’s create a new Go module for our project</p><pre>mkdir pubsub_cloud_func<br>cd pubsub_cloud_func<br>go mod init github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc</pre><p><strong>repository Package</strong></p><p>Define your data access logic in this package.</p><pre>package repository<br><br>import (<br> &quot;cmp&quot;<br><br> &quot;slices&quot;<br><br> &quot;github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc/app/dto&quot;<br>)<br><br>var items = make([]dto.Item, 0, 100)<br><br>type ItemRepo interface {<br> New(i dto.Item)<br> Get(id uint) *dto.Item<br>}<br><br>type ItemRepoImpl struct {<br>}<br><br>func NewItemRepo() ItemRepo {<br> return ItemRepoImpl{}<br>}<br><br>func (repo ItemRepoImpl) Get(id uint) *dto.Item {<br> i, _ := slices.BinarySearchFunc(items, dto.Item{ID: id}, func(e, t dto.Item) int {<br>  return cmp.Compare(e.ID, t.ID)<br> })<br> return &amp;items[i]<br>}<br><br>func (repo ItemRepoImpl) New(i dto.Item) {<br> items = append(items, i)<br>}</pre><p><strong>service Package</strong></p><p>Define your business logic in this package.</p><pre>package service<br><br>import (<br> &quot;errors&quot;<br><br> &quot;github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc/app/dto&quot;<br> &quot;github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc/app/repository&quot;<br>)<br><br>type ItemService interface {<br> New(item dto.Item) error<br>}<br><br>type ItemServiceImpl struct {<br> ItemRepo repository.ItemRepo<br>}<br><br>func NewItemService() ItemService {<br> return ItemServiceImpl{<br>  ItemRepo: repository.NewItemRepo(),<br> }<br>}<br><br>func (srv ItemServiceImpl) New(i dto.Item) error {<br> item := srv.ItemRepo.Get(i.ID)<br> if item != nil {<br>  return errors.New(&quot;item already exists&quot;)<br> }<br><br> srv.ItemRepo.New(i)<br> return nil<br>}</pre><p><strong>utils Package</strong></p><p>Define your utility functions in this package.</p><pre>package pkg<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;log&quot;<br>)<br><br>func StructBuilder[T any](data []byte) (T, error) {<br> var v T<br> err := json.Unmarshal(data, &amp;v)<br> if err != nil {<br>  log.Println(&quot;Failed to unmarshal JSON&quot;, err)<br>  return v, err<br> }<br><br> return v, nil<br>}</pre><h3>Write Cloud Function</h3><p>Now create the cloud_func folder and initialize a Go module for it:</p><pre>mkdir cloud-function<br>cd cloud-function<br>go mod init github.com/chazool/go_medium_samples/pubsub_cloud_func/cloud_func/new_item</pre><p><strong>go.mod File</strong></p><pre>module github.com/chazool/go_medium_samples/pubsub_cloud_func/cloud_func/new_item<br><br>go 1.22.2<br><br>replace github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc =&gt; ../../<br><br>require (<br> github.com/GoogleCloudPlatform/functions-framework-go v1.8.1<br> github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc v0.0.0-00010101000000-000000000000<br> github.com/cloudevents/sdk-go/v2 v2.14.0<br><br>)<br><br>require (<br> cloud.google.com/go/functions v1.15.3 // indirect<br> github.com/google/uuid v1.4.0 // indirect<br> github.com/json-iterator/go v1.1.10 // indirect<br> github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect<br> github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect<br> go.uber.org/atomic v1.4.0 // indirect<br> go.uber.org/multierr v1.1.0 // indirect<br> go.uber.org/zap v1.10.0 // indirect<br>)</pre><p><strong>Implement the Cloud Function</strong></p><p>Create a new Go file for your Cloud Function. Let’s call it new_item.go. This function will be triggered by Pub/Sub messages.</p><pre>package new_item<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br><br> &quot;github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc/app/dto&quot;<br> &quot;github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc/app/service&quot;<br> &quot;github.com/chazool/go_medium_samples/pubsub_cloud_func/pubsubcloudfunc/pkg&quot;<br><br> _ &quot;github.com/GoogleCloudPlatform/functions-framework-go/funcframework&quot;<br> &quot;github.com/GoogleCloudPlatform/functions-framework-go/functions&quot;<br> &quot;github.com/cloudevents/sdk-go/v2/event&quot;<br>)<br><br>func init() {<br> functions.CloudEvent(&quot;newItem&quot;, NewItem)<br>}<br><br>type MessagePublishedData struct {<br> Message PubSubMessage<br>}<br><br>type PubSubMessage struct {<br> Data []byte `json:&quot;data&quot;`<br>}<br><br>func NewItem(ctx context.Context, e event.Event) error {<br> var msg MessagePublishedData<br><br> // Convert event data to MessagePublishedData struct<br> if err := e.DataAs(&amp;msg); err != nil {<br>  log.Printf(&quot;error converting event data: %v&quot;, err)<br>  return fmt.Errorf(&quot;event.DataAs: %w&quot;, err)<br> }<br><br> // Build an Item struct from the message data<br> i, err := pkg.StructBuilder[dto.Item](msg.Message.Data)<br> if err != nil {<br>  log.Printf(&quot;error building item structure: %v&quot;, err)<br>  return fmt.Errorf(&quot;struct builder: %w&quot;, err)<br> }<br><br> // Attempt to add the new item using the service<br> srv := service.NewItemService()<br> if err := srv.New(i); err != nil {<br>  log.Printf(&quot;error occurred while adding new item: %v&quot;, err)<br>  return fmt.Errorf(&quot;adding item: %w&quot;, err)<br> }<br><br> return nil<br>}</pre><h3><strong>Deploying the Cloud Function</strong></h3><p>If you are using any third-party dependencies, you can vendor them using go mod vendor. This will create a vendor directory containing all the dependencies.</p><h4><strong>Create a Pub/Sub Topic</strong></h4><p>Before deploying the Cloud Function, let’s create a Pub/Sub topic.</p><pre>gcloud pubsub topics create new_item</pre><p><strong>Deploy the Cloud Function</strong></p><p>Now, it’s time to deploy your Cloud Function to Google Cloud Platform. Make sure you have the Google Cloud SDK installed and configured with your GCP project.</p><pre>gcloud functions deploy new_item_test \<br>--gen2 \<br>--runtime go122 \<br>--trigger-topic new_item \<br>--source=. \<br>--entry-point=newItem \<br>--region us-central1</pre><p><strong>Conclusion</strong></p><p>That’s it! You’ve now successfully built and deployed a Google Cloud Function triggered by Pub/Sub events using Go, with the ability to reuse common code across functions. This approach enhances scalability, maintainability, and efficiency in your event-driven architecture on Google Cloud Platform.</p><p>For further reference and to explore the code used in this tutorial, you can find the repository <a href="https://github.com/chazool/go_medium_samples/tree/master/pubsub_cloud_func">here</a>.</p><p>— Happy coding! 💻😊 —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1418c860a7d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Multiple Database Connections in Golang]]></title>
            <link>https://chazool.medium.com/managing-multiple-database-connections-in-golang-dc90dcf6f569?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc90dcf6f569</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[turorial]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 12:44:23 GMT</pubDate>
            <atom:updated>2023-09-25T12:44:23.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KfkHZvZuA2JTsjwaUVQsYg.png" /></figure><h3>Introduction</h3><p>As software engineers, often encountered situations where applications need to work with multiple databases, each with its unique requirements and configurations. Efficiently handling these various database connections while adhering to coding best practices is crucial for building robust and easily maintainable applications. In this article, the topic of managing multiple database connections in the Golang will be explored. Insights from software engineering will be shared, demonstrating an approach aligned with SOLID principles, which facilitate the creation of clean and maintainable code.</p><h3>The Challenge: Multiple Database Connections</h3><p>In software development, working with multiple databases like MySQL, PostgreSQL, or others is common. Managing these connections can be challenging due to differences in configuration and requirements. To address this challenge effectively, a step-by-step guide and a practical example will be provided.</p><h4>Step 1: Database Configuration</h4><p>Begin by defining a DBConfig struct to hold the configuration details for each database. These configurations include critical parameters like the database type, user credentials, host, port, and more.</p><pre>// DBConfig represents the configuration for a database.<br>type DBConfig struct {<br> IdentificationName string // IdentificationName is used to obtain the specific database connection.<br> DB                 string   // Database name.<br> User               string   // Database user.<br> Password           string   `json:&quot;_&quot;` // Database password.<br> Host               string   // Database host.<br> Port               string   // Database port.<br> Type               string   // Type of the database (&quot;mysql&quot;, &quot;postgres&quot;, &quot;mssql&quot;, etc.).<br> SSLMode            string   // SSL mode for the database connection.<br> TimeZone           string   // Time zone for the database.<br> dialector          gorm.Dialector // GORM dialector for database configuration.<br>}<br><br>// Connect establishes a database connection based on the provided configuration.<br>func (config *DBConfig) Connect() (DBConnection, error) {<br> db, err := gorm.Open(config.dialector, &amp;gorm.Config{})<br> return db, err<br>}</pre><h3>Step 2: Database Connection Interface</h3><p>Create a DatabaseConnection interface to represent a database connection. This interface includes a Connect method that returns a database connection and an identificationName to uniquely identify the connection.</p><pre>type DBConnection *gorm.DB<br><br>type DatabaseConnection interface {<br>    Connect() (DBConnection, error)<br>}</pre><h3>Step 3: Implementing Database Connections</h3><p>Implement two types of database connections: MySQL and PostgreSQL. Each connection type has its Connect method that configures the database connection parameters based on the provided configuration and returns a GORM DB instance.</p><pre>// MySQLConnection implements DatabaseConnection for MySQL.<br>type MySQLConnection struct {<br> Config *DBConfig<br>}<br><br>// Connect connects to a MySQL database and returns a GORM DB instance.<br>func (m *MySQLConnection) Connect() (DBConnection, error) {<br> dsn := &quot;%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&amp;parseTime=True&amp;loc=%s&quot;<br> m.Config.dialector = mysql.Open(fmt.Sprintf(dsn, m.Config.User, m.Config.Password, m.Config.Host, m.Config.Port, m.Config.DB, m.Config.TimeZone))<br> db, err := m.Config.Connect()<br> return db, err<br>}<br><br>// PostgresConnection implements DatabaseConnection for PostgreSQL.<br>type PostgresConnection struct {<br> Config *DBConfig<br>}<br><br>// Connect connects to a PostgreSQL database and returns a GORM DB instance.<br>func (p *PostgresConnection) Connect() (DBConnection, error) {<br> dsn := &quot;host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=%s&quot;<br> p.Config.dialector = postgres.Open(fmt.Sprintf(dsn, p.Config.Host, p.Config.User, p.Config.Password, p.Config.DB, p.Config.Port, p.Config.SSLMode, p.Config.TimeZone))<br> db, err := p.Config.Connect()<br> return db, err<br>}</pre><h3>Step 4: Creating and Managing Database Connections</h3><p>Create a NewConnection function that generates a new database connection based on the given configuration. This function also automatically performs database migrations to ensure the database schema is up to date.</p><pre>// NewConnection creates a new DatabaseConnection based on the given config.<br>func (config *DBConfig) NewConnection() (DBConnection, error) {<br> var dbConnection DatabaseConnection<br> switch config.Type {<br> case &quot;mysql&quot;:<br>  dbConnection = &amp;MySQLConnection{Config: config}<br> case &quot;postgres&quot;:<br>  dbConnection = &amp;PostgresConnection{Config: config}<br> default:<br>  return nil, fmt.Errorf(&quot;Unsupported database type: %s&quot;, config.Type)<br> }<br><br> // create new connection<br> con, err := dbConnection.Connect()<br> if err != nil {<br>  return nil, err<br> }<br><br> //AutoMigrate dtos<br> err = con.Statement.AutoMigrate(&amp;dto.User{})<br> if err != nil {<br>  return nil, err<br> }<br><br> return con, nil<br>}</pre><h3>Step 5: Using the Database Connections</h3><p>In the main function, initialize and utilize the database connections. Access a specific connection by its identificationName and perform necessary database operations.</p><pre>func init() {<br> // Initialize database connections during program startup.<br> configs.InitDBConnections()<br>}<br><br>func main() {<br> users := []dto.User{<br>  {<br>   UserName: &quot;user1&quot;,<br>   Password: &quot;test1&quot;,<br>  },<br>  {<br>   UserName: &quot;user2&quot;,<br>   Password: &quot;test2&quot;,<br>  },<br> }<br><br> // Create a new UserRepository with a specified connection name<br> repo := repo.NewUserRepo(&quot;TEST_POSTGRES_CON&quot;)<br><br> // save users<br> err := repo.Save(users...)<br> if err != nil {<br>  return<br> }<br><br> // get all users<br> users, err = repo.FindAll()<br> if err != nil {<br>  return<br> }<br><br> // print users<br> for _, user := range users {<br>  fmt.Printf(&quot;%+v\n&quot;, user)<br> }<br><br> // Set up a channel to listen for OS signals (e.g., Ctrl+C)<br> c := make(chan os.Signal, 1)<br> signal.Notify(c, os.Interrupt, syscall.SIGTERM)<br> // Wait for a signal (e.g., Ctrl+C) to gracefully exit the program<br> &lt;-c<br><br> // Close database connections when the program terminates.<br> defer configs.CloseDBConnections()<br>}</pre><h3>Conclusion</h3><p>Managing multiple database connections in Golang is a common challenge in software development. By following the steps outlined in this article and utilizing the provided example code, efficiently handle various database types while maintaining clean and maintainable code.</p><p>With this approach, confidently work with multiple databases in Golang projects, ensuring scalability and maintainability as the application grows. Clean and maintainable code is essential for the success of any software project, and mastering the management of multiple database connections is a valuable skill for software engineers.</p><p><a href="https://github.com/chazool/go_medium_samples/tree/master/multi_db_coonnection_manager">Managing Multiple Database Connections Repository</a></p><p>— happy coding 😉 —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc90dcf6f569" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Pitfalls of Directly Using Third-Party Modules in Your Golang Production Code]]></title>
            <link>https://chazool.medium.com/the-pitfalls-of-directly-using-third-party-modules-in-your-golang-production-code-56815a007c1c?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/56815a007c1c</guid>
            <category><![CDATA[risk]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 17:04:21 GMT</pubDate>
            <atom:updated>2023-09-10T01:22:23.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j82-QEvhcZdpvdfk9WY5Dw.png" /></figure><h3>Introduction</h3><p>Third-party modules have become an integral part of modern software development, offering a way to extend functionality without reinventing the wheel. In the realm of Golang development, third-party modules provide a valuable shortcut to building robust applications efficiently. They range from database drivers like GORM and logging libraries such as zap, to utility packages like viper for configuration management. However, while they offer convenience, directly integrating third-party modules into your production code might not be the best strategy. In this article, we explore the potential problems and risks of this approach and propose an alternative: utilizing custom packages or code.</p><h3>The Problems</h3><p>Directly incorporating third-party modules into your codebase can lead to several challenges:</p><p><strong>Compatibility Issues:</strong> Third-party modules can evolve independently of your application, causing potential mismatches between your code and module updates. These changes might result in breaking your existing codebase or introducing subtle bugs. For instance, the transition from the `<em>ioutil</em>` package to the `<em>io</em>` and `<em>os</em>` packages in Go 1.16.</p><p><strong>Stability and Security Risks:</strong> Modules, even well-maintained ones, can be deprecated or abandoned by their maintainers. This can leave your code susceptible to security vulnerabilities or performance issues. For example, the `<em>jaeger-client</em>` library is deprecated and will no longer receive updates, which could affect the stability and security of your application if you continue to rely on it.</p><p><strong>Replacement:</strong> Newer and better alternatives can replace existing modules, offering enhanced features or efficiency. For instance, the introduction of the `<em>slog</em>` package in Go 1.21 as a replacement for the `<em>zap` </em>package for structured logging.</p><h3>How to Fix It</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rASOm17blcCJcIczGpN9mw.jpeg" /><figcaption>golang third-party package manager</figcaption></figure><p>To mitigate the issues of directly using third-party modules, consider the following strategies:</p><p><strong>Abstraction: </strong>Build custom packages that encapsulate third-party module functionality and expose a stable API for your code. This allows for easier replacement of modules without major code changes. For instance, you can create a custom package that uses GORM internally for database access but provides a simplified CRUD interface for your models.</p><p><strong>Implementation: </strong>Craft your own code to fulfill your application’s requirements, bypassing third-party modules entirely. This grants you full control and ownership over your codebase and the ability to optimize it for your unique needs. For example, instead of relying on external logging libraries, create your own logging functions using Go’s standard `log` package.</p><p>Guidelines for creating custom packages or code include comprehensive documentation, thorough testing, proper versioning, and compliance with licensing requirements.</p><h4>Sample Implementation</h4><p>The code has been effectively decoupled from the specific database library (in this example, GORM). This abstraction allows us to switch to a different database library in the future by implementing functions specific to the new library within the ‘configs’ package. Whether we decide to use a different SQL database library, a NoSQL database, or any other data storage solution, we can create a new database provider within ‘configs.’ This provider can encapsulate interactions with the new database library without requiring extensive changes to the repository or other parts of the application.</p><p>By implementing this additional level of abstraction, Go production code gains greater flexibility and maintainability. It can adapt to changing requirements or take advantage of new database technologies without compromising the overall structure and functionality of the application. This approach follows the principle of separating concerns and makes the codebase more robust and adaptable in the long run</p><p><strong>Package </strong><strong>configs:</strong> Encapsulate the database functionality using a custom package and interface.</p><pre>package configs<br><br>import (<br> &quot;fmt&quot;<br> &quot;modulemanager/dto&quot;<br><br> &quot;gorm.io/driver/postgres&quot;<br> &quot;gorm.io/gorm&quot;<br>)<br><br>var dbCon DBConnection<br><br>type DBConnection *gorm.DB<br><br>// DBConfig defines the database configuration parameters.<br>type DBConfig struct {<br> _        struct{}<br> Host     string<br> User     string<br> Password string `json:&quot;_&quot;`<br> Port     string<br> DB       string<br> SSLMode  string<br> TimeZone string<br>}<br><br>type DBOperator struct {<br> Con DBConnection<br>}<br><br>// NewConnection initializes the database connection based on the provided config.<br>func (db *DBConfig) NewConnection() (DBConnection, error) {<br> dsn := &quot;host=%s user=%s password=%s dbname=%s port=%s sslmode=%s TimeZone=%s&quot;<br> dialector := postgres.Open(fmt.Sprintf(dsn, db.Host, db.User, db.Password, db.DB, db.Port, db.SSLMode, db.TimeZone))<br> con, err := gorm.Open(dialector, &amp;gorm.Config{})<br> if err != nil {<br>  return nil, err<br> }<br><br> con.AutoMigrate(&amp;dto.User{})<br><br> return con, nil<br>}<br><br>// Save saves the given value to the database.<br>func (db *DBOperator) Save(value interface{}) error {<br> return db.Con.Statement.Create(value).Error<br>}<br><br>// Find finds and retrieves data from the database and stores it in dest.<br>func (db *DBOperator) Find(dest interface{}) error {<br> return db.Con.Statement.Find(dest).Error<br>}<br><br>// InitDBConnection initializes the database connection.<br>func InitDBConnection() {<br> dbConfig := DBConfig{<br>  Host:     &quot;localhost&quot;,<br>  User:     &quot;postgres&quot;,<br>  Password: &quot;postgres&quot;,<br>  Port:     &quot;5432&quot;,<br>  DB:       &quot;testapp&quot;,<br>  SSLMode:  &quot;disable&quot;,<br>  TimeZone: &quot;Asia/Shanghai&quot;,<br> }<br> con, err := dbConfig.NewConnection()<br> if err != nil {<br>  return<br> }<br> dbCon = con<br>}<br><br>// GetDBConnection returns the database connection.<br>func GetDBConnection() DBConnection {<br> return dbCon<br>}</pre><p><strong>Package </strong><strong>main: </strong>Use the custom repository and database connection.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;modulemanager/configs&quot;<br> &quot;modulemanager/dto&quot;<br> &quot;modulemanager/repo&quot;<br>)<br><br>func init() {<br> // init db connection<br> configs.InitDBConnection()<br>}<br><br>func main() {<br> users := []dto.User{<br>  {<br>   UserName: &quot;user1&quot;,<br>   Password: &quot;test1&quot;,<br>  },<br>  {<br>   UserName: &quot;user2&quot;,<br>   Password: &quot;test2&quot;,<br>  },<br> }<br><br> repo := repo.NewUserRepo()<br><br> // save users<br> err := repo.Save(users...)<br> if err != nil {<br>  return<br> }<br><br> // get all users<br> users, err = repo.FindAll()<br> if err != nil {<br>  return<br> }<br><br> // print users<br> for _, user := range users {<br>  fmt.Printf(&quot;%+v\n&quot;, user)<br> }<br><br>}</pre><h3>Conclusion</h3><p>Directly integrating third-party modules into your Golang production code can lead to a host of issues, including breaking changes, abandonment, and the risk of replacement. However, by embracing custom packages or code, you can enjoy numerous benefits, including increased reliability, enhanced security, improved performance, and elevated code quality. Taking the time to develop custom solutions tailored to your application’s needs ensures a smoother development process and a more sustainable codebase in the long run.</p><p><a href="https://github.com/chazool/go_medium_samples/tree/master/third_party_module_manager">Third Party Module Manager Repository</a></p><p>— happy coding 😉 —</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56815a007c1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JVM — Class Loader Subsystem]]></title>
            <link>https://chazool.medium.com/jvm-class-loader-subsystem-e6bc4f539066?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6bc4f539066</guid>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 19:36:28 GMT</pubDate>
            <atom:updated>2021-06-09T19:36:28.588Z</atom:updated>
            <content:encoded><![CDATA[<h3>JVM — Class Loader Subsystem</h3><p>In Java Virtual machine it is necessary to have a class loader subsystem. .class files are read and loaded with this class loader subsystem and it saves the bytecode in the JVM method area</p><ol><li>Loading</li><li>Linking</li><li>Initialization</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hUvhEB_mAYMrENM_Rh3N6g.png" /><figcaption>Class Loader Subsystem</figcaption></figure><h3>Loading</h3><p>As the Class loader subsystem reads class files which are stored in the hard disk, it performs the loading functionality.</p><ul><li>Fully qualified name of class</li><li>Fully qualified name of immediate parent class</li><li>Methods info</li><li>Variable info</li><li>Constructor info</li><li>Modifiers info</li><li>Constant pool info</li><li>whether .class file represents class or Interface or enum</li></ul><p>Storing these corresponding information in the method area can be defined as loading. In general it means storing corresponding binary data and reading the <em>.class</em> files.</p><p>When the class files are loaded the JVM creates an object for the class which is loaded, on the Heap Memory of type <em>java.lang.Class</em>.</p><p>When a programmer needs to get the method info or variable info or Constructor info, these created class objects are used.</p><h3>Linking</h3><p>Linking consists of three activities</p><ol><li>verify (verification)</li></ol><p>2. prepare (preparation)</p><p>3. resolve (resolution)</p><p>These three main performances are consisted in linking</p><ul><li>that class or interface,</li><li>its direct superclass,</li><li>its direct super interfaces, and</li><li>its element type (if it is an array type), if necessary.</li></ul><p>preparing and verifying the above is the process of linking. There is an optional area in linking as resolution of symbolic references in the class or interface.</p><blockquote><em>As linking involves the allocation of new data structures, it may fail with an OutOfMemoryError.</em></blockquote><h4>1. Verify (Verification)</h4><p>Verification is a process that verifies the validity of the generated class file. Whether it is compiled by a valid compiler or not, whether the .class file is properly formatted or not. It ensures the binary reputation of the class is structurally well generated. Bytecode verifier is the internal build verifier which is responsible for the verification process. This is built within the class loader subsystem</p><p>runtime exception java.lang.VerifyError occurs in instances where the bytecode verifier fails. <em>An error thrown is an instance of LinkageError (or its subclass).</em></p><blockquote><em>In making Java a secured language, </em><strong><em>Bytecode verifier </em></strong><em>plays an ultimate role. When a class file is changed or updated manually by any third party, the Bytecode verifier finds that the class file is not created or generated through a valid compiler. When the process of Verification fails, we will get runtime exception saying</em><strong><em> </em></strong><em>java.lang.VerifyError</em></blockquote><h4>2. Prepare (Preparation)</h4><p><em>In this phase, allocation of the memory for class level or interface level static variables and assign default values by JVM will happen.</em></p><p><em>Only default values will be assigned to static variables in this process as the original values will be assigned in the initialization process.</em></p><h4>3. Resolve (Resolution)</h4><p>It is the process of replication of symbolic names in our program with the original memory reference from the method area.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0605d7abf372800a128062d0d14190a0/href">https://medium.com/media/0605d7abf372800a128062d0d14190a0/href</a></iframe><p>For the above class, class loader load <em>Testing.class, String.class,Student.class, Object.class. </em>The name of these classes are stored in constone pool <em>Testing </em>class in resolution face this name are replation with the original memory level reference of method area.</p><p>There are few errors which can occur in subclass of java.lang.LinkageError.</p><p>IncompatibleClassChangeError is thrown when a symbolic reference is resolved but results in a conflict of definitions. NoSuchMethodError. Is thrown by method resolution when the method lookup fails. When the method lookup succeeds and the method is abstract, but Class is not abstract, then AbstractMethodError is thrown by the method resolution.</p><h3>Initialization</h3><p>In the Initialization phase, all static variables are assigned with original values and static blocks will be executed from parent to child and from top to bottom.</p><p>While loading, linking and initialization, if any error occurs, we will get a runtime exception saying java.lang.LinkageError or its subclass java.lang.VerifyError.</p><h3><strong><em>Type Of Class Loader</em></strong></h3><p>Class loader subsystem contain following 3 type of class loaders</p><ul><li>Bootstrap Class Loader | Primordial Class Loader</li><li>Extension Class Loader</li><li>Application Class Loader | System Class loader</li></ul><h4><strong>1. Bootstrap Class Loader — Primordial Class Loader</strong></h4><p>Bootstrap class loader is responsible to load core JAVA API classes that is class presenting <strong><em>rt.jar</em></strong></p><p><strong><em>jdk &gt;&gt; jre &gt;&gt; lib &gt;&gt; rt.jar — </em></strong>This location is called bootstrap class path.</p><p>That is bootstrap loader is a responsible loader the class is from bootstrap class path.</p><p>Bootstrap class loader, is by default available with every JVM, it is implemented in native languages like C or C++ under not implemented in JAVA.</p><h4><strong>2. Extension Class Loader</strong></h4><p>Extension Class loader is the child class bootstrap class loader. Extension class responsible to load class from extension class path.</p><p><strong>jdk &gt;&gt; jre &gt;&gt; lib &gt;&gt; ext &gt;&gt; *.jar</strong></p><p>extension class loader is implemented in java. Under the responsible .class file is <em>sun.misc.Louncher$ExtClassLoader.class</em></p><h4><strong>3. Application Class Loader | System Class Loader</strong></h4><p>Application class loader is the child class of Extension class loader. This class loader is responsible for loading class loaders from the application class path. It internally uses Environment variable class path.</p><p>Application class loader is implemented in java under the responding .class file name is <em>sun.misc.Louncher$AppClaasLoader.class.</em></p><h3><strong>How to Work Class Loader</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQZTKKGfeV1bD5Dio5iyUg.png" /><figcaption>Class Loader Delegation Algorithm</figcaption></figure><p>Class loader follows delegation Hierarchy principle. Whenever a JVM comes to a particular class 1st it will check whether the responding .class file is already loaded or not, if it is already loaded in the method area the JVM will consider that loaded class.</p><p>If it does not load the JVM request class loader subsystem to the lord particular class, then class loader subsystem handover requests to Application class loader.</p><p>Application class loader delegates the request to Extension class loader which intron delegation request to bootstrap class loader.</p><p>Then the bootstrap class loader will search in the bootstrap class path. If it is available the responding .class will be loaded by bootstrap class loader. If it is not available then the bootstrap class loader delegates the request to the extension class loader.</p><p>extension class loader will search in extension class path. if it is available then it will load otherwise extension class loader delegated request to application class loader.</p><p>Application class loader will search in application class path. If it is available then it will be loaded otherwise it will get a runtime Exception NoClassDefFountException or ClassNotFoundException.</p><h3>Reference</h3><ul><li>JVM Architecture: JVM Class loader and Runtime Data Areas : <a href="https://www.javacodegeeks.com/2018/04/jvm-architecture-jvm-class-loader-and-runtime-data-areas.html">https://www.javacodegeeks.com/2018/04/jvm-architecture-jvm-class-loader-and-runtime-data-areas.html</a></li><li>Class Loader in Java : <a href="https://www.geeksforgeeks.org/classloader-in-java/">https://www.geeksforgeeks.org/classloader-in-java/</a></li><li>The JVM Architecture Explained : <a href="https://dzone.com/articles/jvm-architecture-explained">https://dzone.com/articles/jvm-architecture-explained</a></li><li>Loading, Linking, and Initializing : <a href="https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html">https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html</a></li><li>Class Loader in Java : <a href="https://www.javatpoint.com/classloader-in-java">https://www.javatpoint.com/classloader-in-java</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6bc4f539066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Collection Framework]]></title>
            <link>https://chazool.medium.com/java-collection-framework-1a26b56a310a?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a26b56a310a</guid>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 06:23:22 GMT</pubDate>
            <atom:updated>2021-06-07T06:23:22.988Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>01. Collections</strong></h3><p>An array is an indexed Collection of a fixed number of homogeneous data elements. The Main advantage of Arrays is we can represent multiple values with a single variable. So that reusability of the code will be improved.</p><p>Arrays are fixed in size i.e. once create an array with some size there is no chance of increasing or decreasing its size based on our requirement. Hence to use arrays compulsory we should know the size in advance which may not always be possible always.</p><p>Arrays can hold only homogeneous data elements.</p><p>Student [] s = new Student [10000];</p><p>s[0] = new Student; (correct)</p><p>s[1] = new Customer(); (wrong)</p><p>But We can resolve this problem by using object Arrays.</p><p>Object [] o = new Object [10000];</p><p>o[0] = new Student();</p><p>o[1] = new Customer();</p><p>Arrays Concept is not implemented based on some standard data structure hence readymade method support is not available for every requirement we have to write the code explicitly. Which is the complexity of programming.</p><p>To Overcome the above limitations of Arrays we should go for Collections.</p><p>Collections are growable in nature. I.e Based on our requirement we can increase or decrease the size.</p><p>Collection can hold both homogeneous and Heterogeneous elements.</p><p>Every Collection class is implemented based on some standard data structure. Hence readymade method support is available for every requirement. Being a programmer we have to use this method and we are not responsible to provide implementation</p><h3><strong>02. Collection Framework</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9g9RyDXO8A2n-KulJm3XtA.png" /></figure><h4><strong>Collection — Interface :</strong></h4><ul><li>If want to represent a group of individual objects as a single entity then should go for Collection.</li><li>Collection interface defines the most common methods which are applicable for any Collection object.</li><li>In general the collection interface is considered as the root interface of Collection Framework.</li></ul><p><em>There is no concrete class which implements the collection interface directly.</em></p><h4><strong>List — Interface</strong></h4><ul><li>List is the child interface of collection.</li><li>If Want to represent a group of individual object as a single entry where duplicate are allowed and insertion order preserved then should go for list</li><li>Differentiate duplicate by using index</li><li>Preserve insertion order by using index, hence index play very important role in list interface.</li></ul><p><em>Vector and Stack classes are re-engineer in 1.2 to implement list interface.</em></p><h4><strong>Set — Interface</strong></h4><ul><li>It is the child interface of Collection.</li><li>If want to represent a group of individual objects as a single entity where duplicates are not allowed and insertion order not preserved then should go for Set.</li><li>The interface doesn’t contain any new methods. So we have to use only Collection interface methods.</li></ul><h4><strong>Queue — Interface</strong></h4><ul><li>It is child interface of Collection.</li><li>If we want to represent a group of individual objects prior to processing then we should go for Queue.</li><li>For this First in First out requirement Queue is best coise.</li></ul><p>* Usually Queue follows First in First out order but based on our requirement we can implement our own Priority order also. (PriorityQueue).</p><h4><strong>Map — Interface</strong></h4><ul><li>Map is not the child interface of Collection.</li><li>If we want to represent a group of individual objects as key value pairs then should go for Map.</li><li>Duplicated keys are not allowed but values can be duplicated</li><li>Both Key and Value are Object Only</li><li>Each key value pair is call Entry</li></ul><h3><strong>03. List</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*CYz5kdyKqItWOXAhJ0J1sQ.png" /></figure><h4><strong>ArrayList</strong></h4><ul><li>The underlined data structure Resizable Array or Growable Array</li><li>Duplicates are allowed.</li><li>Insertion order is preserved.</li><li>Heterogeneous objects are allowed [except TreeSet &amp; TreeMap everywhere heterogeneous objects are allowed].</li><li>Null insertion is possible.</li></ul><h4><strong>LinkedList</strong></h4><ul><li>The underlying data structure is Double Linked List.</li><li>Insertion order is preserved</li><li>Duplicates are allowed.</li><li>Heterogeneous Objects are allowed.</li><li>Null insertion is possible.</li><li>LinkedList implements Serializable and Cloneable interfaces but not RandomAccess interface.</li><li>LinkedList is the best choice if our frequent operation is insertion or deletion in the middle.</li><li>LinkedList is the worst choice if our frequent operation is retrieval operation.</li></ul><h4><strong>Vector</strong></h4><ul><li>The underlying Data structure for the vector is resizable array or growable array.</li><li>Duplicate objects are allowed.</li><li>Insertion order is preserved.</li><li>‘null’ insertion is possible.</li><li>Heterogeneous objects are allowed.</li><li>Vector class implemented Serializable, Closeable and RandomAccess Interfaces.</li><li>Most of the methods present in Vector are synchronized. Hence the Vector object is Thread-safe.</li><li>Best choice if the frequent operation is retrieval.</li></ul><h4><strong>Stack</strong></h4><ul><li>It is a child class of Vector.</li><li>It is Specially designed class for Last in First Out order (LIFO)</li></ul><h3><strong>04. Set</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*5I93kgIW7dg14xNeZK9-UQ.png" /></figure><h4><strong>SortedSet</strong></h4><ul><li>It is the child interface of Set.</li><li>If want to represent a group of individual objects as a single entity where duplicates are not allowed but all objects should be inserted according to some sorting orde then should go for SortedSet.</li></ul><h4><strong>NavigableSet</strong></h4><ul><li>It is the child interface of SortedSet that defines several methods for navigation purposes.</li></ul><h4><strong>SortedSet</strong></h4><ul><li>It is the child interface of Set</li><li>If want to represent a group of individual objects according to some sorting order and duplicates are not allowed then should go SortedSet.</li><li>Default natural sorting order for numbers Ascending order and for String alphabetical order.</li><li>Can Apply the above methods only SortedSet implemented class object. That is on the TreeSet object.</li></ul><h4><strong>TreeSet</strong></h4><ul><li>The underlying data structure for TreeSet is Balanced Tree.</li><li>Duplicate objects are not allowed.</li><li>Insertion order not preserved, but all objects will be inserted according to some sorting order.</li><li>Heterogeneous objects are not allowed. If we are trying to insert heterogeneous objects then we will get a runtime exception saying ClassCastException.</li><li>For empty TreeSet as the first element null insertion is possible. But After inserting that null if we are trying to insert any other element will get NullPointerException.</li><li>For Non empty TreeSet if trying to insert Null then will get NullPointerException.</li></ul><h4><strong>HashSet</strong></h4><ul><li>The underlying data structure is Hashtable.</li><li>Duplicates are not allowed. If trying to insert duplicates, won’t get any compile time or runtime errors. add() method simply returns false.</li><li>Insertion order is not preserved and all objects will be inserted based on the hash-code of objects. * Heterogeneous objects are allowed.</li><li>null ‘ insertion is possible.</li><li>implements Serializable and Cloneable interfaces but not RandomAccess.</li><li>HashSet is the best choice, if our frequent operation is Search operation.</li></ul><h4><strong>LinkedHashSet</strong></h4><ul><li>It is the child class of Hashset</li><li>The Underlying data structure is Hash Table + Linked List</li><li>Insertion Order is Preserved</li><li>Best choice to develop cache based applications, where duplicates are not allowed and Insertion order must be preserved.</li></ul><h3><strong>05. Queue</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*uHpkUzkk7SPafqBibktzCA.png" /></figure><h4><strong>PriorityQueue</strong></h4><ul><li>If we want to represent a group of individual objects prior to processing according to some priority then we should go PriorityQueue.</li><li>The Priority can be default natural sorting order or customized sorting order defined by comparator.</li><li>Insertion order is not preserved under it based on some Priority.</li><li>Duplicate objects are not allowed.</li><li>If we are depending on default natural order compulsory object should be Homogeneous or comparable otherwise we will get a RuntimeException saying ClassCastException.</li><li>If we are defining our own sorting by comparator then objects need not be Homogeneous under comparable.</li><li>Null is not allowed.</li></ul><h3><strong>06. Map</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*TTvgdY9-nYK8Ko-MD3zRQQ.png" /></figure><h4><strong>SortedMap</strong></h4><ul><li>It it the child interface of map</li><li>If want to represent a group of key value pairs according to some sorting order of keys then should go for SortedMap</li></ul><h4><strong>NavigableMap</strong></h4><ul><li>It is the child interface of SortedMap.</li><li>It defines several utility methods for navigation purposes.</li></ul><h4><strong>HashMap</strong></h4><ul><li>Underlying data structure is HashTable</li><li>Insertion order is not preserved. Under it is base base on Hash Code is Key</li><li>Duplicate Keys are not allowed , but Values can be duplicated.</li><li>Heterogeneous objects are allowed , for both key and values.</li><li>Null allowed for key , Only one time</li><li>Null allowed values, any number of times</li><li>Hashmap implements Serilizeble , Cloneable interface but not RandomAccess</li><li>Empty Hashmap Default Initial Capacity 16.</li><li>The default load factor of HashMap is 0.75</li><li>Every Method presenting HashMap is Not a Synchronizer.</li><li>Multiple threads are allowed to operate on Hashmap objects. It is Not thread safe.</li></ul><h4><strong>LinkedHashMap</strong></h4><ul><li>It is the Child class of HashMap</li><li>It is exactly same as HashMap including Method and Construction.</li><li>Underlying data structure is LinkedList and HashTable.</li><li>Insertion order is preserved.</li></ul><h4><strong>IdentityHashMap</strong></h4><p>It is exactly the same as the HashMap Including method and Constructor. Except following deference.</p><p>In the case of normal Hashmap JVM will use the .equal method used to identify duplicate keys. But in the case of IdentityHashMap JVM will be used == operator to Identify duplicate keys( Reference Comparisons).</p><h4><strong>WeekHashMap</strong></h4><p>The exact same HashMap is accepted following the difference.</p><p>In the case of HashMap even though objects don’t have any reference it is eligible for garbage collector it is associated with HasMap.That is HashMap dominant Garbage Collector.</p><p>But in the case of WeekHashMap if Object doesn’t contain any references it is eligible Garbage Collector evon those objects associated with WeekHashMap that is Garbage Collector dominate WeekHashMap.</p><h4><strong>SortedHashMap</strong></h4><ul><li>It is child interface of Map</li><li>If want to represent a group Key,Value pairs according to some sorting of keys then we should go SorterdMap.</li><li>Sorting is based on the Key but not based on Values.</li></ul><h4><strong>TreeMap</strong></h4><ul><li>Underlying data structure is RedBlackTree</li><li>Insertion Order is not preserved, under it is based on some sorting order of keys.</li><li>Duplicate objects are not allowed, but values can be duplicated.</li><li>Depending on Default Natural sorting order. The n key should be Homogeneous under Comparable otherwise we will get a runtime exception saying ClassCastException.</li><li>If we are defining our own sorting by comparator then keys need not be Homogeneous under Comparable, we can take Heterogeneous non comparable objects also.</li><li>Depending on default natural sorting order or customized sorting order there are restrictions for values. we can take Heterogeneous non comparable objects also.</li><li>New Empty TreeMap if we are trying to insert an Entry with a null key then we will get a RuntimeException , saying NullPointerException.</li><li>For Empty TreeMap add the first entry with the null key is allowed. But after inserting that entry if we are trying to insert any other entry then we will get a RuntimeException saingNullpointException.</li><li>Null is Not Allowed for Key, But for Values we can use any no of times.</li></ul><h4><strong>NavigableMap</strong></h4><p>The NavigableMap child interface of SortedMap defines several methods for navigation purposes.</p><h4><strong>HashTable</strong></h4><ul><li>Underlying data structure is HashTable</li><li>Insertion order is not preserved. Under it is based on Hash Code on Keys.</li><li>Duplicate keys are not allowed. Values can be duplicated..</li><li>Heterogeneous objects are allowed. Both keys and values.</li><li>Null is not allowed for both key and values. Otherwise we will get a RuntimeException saying NullPointException.</li><li>It implements Serializeble and Cloneable interfaces. But not RandomAccess.</li><li>Every method presenting Hashtable is Synchronized. Under HashTable is Thread Safe.</li></ul><h4><strong>Properties</strong></h4><ul><li>In our program if anything which changes frequently like UserName Password Email, MobileNo , etc is not recommended to hard code in the program because if there is any change to reflect that change recompilation, rebuild, on the redeploy application are required, even some time server restart also required.</li><li>Can overcome this problem with the Properties file. Search type of variable thinks we have to configure in the property files. From the property file we have to read into the java program under which we can access those properties. The main advantage of this approach is effort. There is a change in the property file to reflect that change just redeployment is enough.</li><li>Can use Java Property Objects which are coming from Property Files.</li><li>In Normal Map Like HashMap, HashTable TreeMap Key Value can be any Object Type , but in the case of Properties key and Value should be String type.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a26b56a310a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java]]></title>
            <link>https://chazool.medium.com/multithreading-in-java-a0e1a9e8a1e0?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e1a9e8a1e0</guid>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 06:23:14 GMT</pubDate>
            <atom:updated>2021-06-07T06:23:14.079Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Multitasking</strong></h3><p>If we can execute several tasks simultaneously we call that concept multitasking. There are two types of multitasking.</p><ol><li>Process Based Multitasking</li></ol><p>2. Thread Based Multitasking</p><h4>Process Based Multitasking</h4><p>Process based multitasking is the execution of multiple tasks at the same time, each of which is a separate independent program (process).</p><p><strong>Example </strong>: We can listen to audio music from the same system while typing a java application in the editor. We can also download a file from the internet at the same time. All of these duties will be completed at the same time and in a separate order. As a result, multitasking is based on processes.</p><p>At the operating system level, Process based multitasking is very efficient.</p><h4>Thread Based Multitasking</h4><ul><li>Thread based multitasking refers to the execution of many tasks at the same time, where each task is a different independent part of the same program, and each independent part is referred to as a thread.</li><li>A <strong>thread</strong> is the unit of execution within a process. A process can have anywhere from just one <strong>thread</strong> to many <strong>threads</strong>.</li><li>Threads use a shared memory region rather than allocating a distinct memory region, which saves memory and allows for faster context switching across threads than processes</li><li>It’s best used at the programming level.</li><li>As java provides inbuilt support for multithreading with rich API it is very convenient to develop multithreaded applications in java</li></ul><p><strong>Multithreading</strong></p><ul><li>Multithreading in Java is a process of executing multiple threads simultaneously</li><li>A thread is the smallest unit of processing and is a lightweight sub process. It has a distinct execution route.</li><li>A thread is executed within the process, as illustrated in the diagram above. Between the threads, there is context switching.</li><li>Within the OS, there can be several processes, and each process can have many threads.</li><li>Multithreading’s main goal is to maximize CPU utilization by allowing two or more sections of a program to run at the same time.</li><li>A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.</li></ul><h4>Advantages and Applications of Multithreading</h4><ul><li>The basic goal of multitasking, whether it’s process-based or thread-based, is to minimize the system’s response time and improve its performance.</li><li>Because threads are independent and many operations can be performed at the same time, it does not cause the user to be blocked.</li><li>It saves time by allowing to do multiple operations at once.</li><li>Because threads are self-contained, an exception in one thread has no impact on other threads.</li><li>The main important application areas of multithreading are:</li></ul><p><em>— To develop multimedia graphics</em></p><p><em>— To develop animations</em></p><p><em>— To develop video games.</em></p><p><em>— To develop web servers and application servers, etc</em></p><h3>Defining a Thread</h3><p>The Thread class, its methods, and its companion interface, Runnable, are the foundations of Java’s multithreading system. We can define a thread in the following two ways:</p><ol><li>By extending Thread class</li><li>By implementing Runnable interface</li></ol><p>The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c355a467783568c207fd8c0156773ca/href">https://medium.com/media/2c355a467783568c207fd8c0156773ca/href</a></iframe><h4>Thread Scheduler</h4><ul><li>It is a component of the JVM that is in charge of thread scheduling. That is, if numerous threads are ready to be executed, the thread scheduler determines the order in which they will be processed.</li><li>We can’t expect the thread scheduler to follow an exact methodology. It differs from one JVM to the next. As a result, we can’t assume exact thread execution order or output.</li><li>As a result, there is no guarantee of exact output when it comes to multithreading.</li><li>The thread scheduler schedules the threads mostly using preemptive or time slicing scheduling.</li><li>When using preemptive scheduling, the highest priority task runs until it enters the waiting or dead states, or until a higher priority job is created.</li><li>In time slicing, a job runs for a predetermined amount of time before returning to the pool of ready tasks.</li></ul><h4>Thread class start() method</h4><p>Is responsible to register the thread with thread scheduler and all other mandatory activities. There is no way to start a new thread in Java without first performing the thread class start method. It calls the run() method.</p><p>The Thread class start function is considered the heart of multithreading because of this. A thread’s life cycle has numerous stages, and threads exist in a variety of states.</p><ul><li>It is possible for a thread to be active.</li><li>As soon as it receives CPU time, it will be ready to run.</li><li>The activity of a running thread can be temporarily halted by suspending it.</li><li>A thread that has been suspended can then be resumed, allowing it to continue where it left off.</li><li>When a thread is waiting for a resource, it can become blocked.</li><li>A thread can be terminated at any point, halting its operation immediately. A thread cannot be restarted once it has been terminated.</li></ul><h3>Thread Life Cycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxojKRqr-c-9boFvGky_wQ.png" /><figcaption>Thread Life Cycle</figcaption></figure><h4><strong>Thread States</strong></h4><ul><li>New (Born) State: If create a new instance of Thread, it will be in a new state.class, but before the start() method is called. When a thread instance is created.It will be in the “New” state after it is created.</li><li>Runnable (Ready) State: The thread is in a runnable state after calling the start() method, but it has not been picked as the running thread by the thread scheduler. The thread is in the “Runnable” state when it is started.</li><li>Running State: The thread is in running state if the thread scheduler has selected it. When the thread is running, it is called “Running” state</li><li>Waiting (Blocked) State: This is the state when the thread is still alive, but is currently not eligible to run. When the thread is put on hold or it is waiting for the other thread to complete, then that state will be known as “waiting” state.</li><li>Terminated (Dead) State: A thread is in terminated or dead state when its run() method exits. When the thread is dead, it will be known as “terminated” state</li></ul><h4>The Main Thread</h4><p>When a Java application starts, one thread is instantly active. This is commonly referred to as the main thread of program because it is the first one to run when application starts.</p><p>It is the thread from which other “child” threads will be spawned.Often, it must be the last thread to finish execution because it performs various shutdown actions.</p><p>Although program’s main thread is established automatically when it starts, can control it with a Thread object. To do so, must first gain a reference to it by invoking the public static member of Thread currentThread( ). Here’s how it looks in its most basic form: currentThread static Thread ( )</p><p>This method returns a reference to the thread in which it is called. Once have a reference to the main thread, can control it just like any other thread.</p><h4>sleep() method</h4><p>The sleep( ) function suspends execution of the thread from which it is called for the provided number of milliseconds.</p><ul><li>Its general form is shown here:</li></ul><p><em>static void sleep(long milliseconds) throws InterruptedException</em></p><p>In milliseconds, the number of milliseconds to suspend is provided. An InterruptedException may be thrown by this procedure.</p><ul><li>A second form of the sleep( ) method is given next, which allows to select the period in milliseconds and nanoseconds:</li></ul><p><em>static void sleep(long milliseconds, int nanoseconds) throws InterruptedException</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41a6ab57c8d88cb25aad2447bef87a75/href">https://medium.com/media/41a6ab57c8d88cb25aad2447bef87a75/href</a></iframe><h4>setName() and getName() methods</h4><ul><li>In Java, each thread has a name. It could be a JVM-generated default name or a user-defined name.</li><li>Thread-0, Thread-1, and so on will be the default names.</li><li>setName() can be used to specifically set a thread’s name.</li><li>The name of a thread can be obtained by executing getName ( ).</li><li>These methods are Thread class members and are declared as follows:</li></ul><p><em>— public final void setName(String threadName);</em></p><p><em>— public final String getName( );</em></p><h3><strong>Creating a Thread by implementing the Runnable Interface</strong></h3><ul><li>Implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and will put complete business logic inside this method. Following is a simple syntax of the run() method −<strong> <em>public void run( );</em></strong></li><li>As a second step, Instantiate a Thread object using the following constructor − <strong><em>Thread(Runnable threadObj, String threadName)</em></strong> Or <strong><em>Thread(Runnable threadObj)</em> </strong>Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.</li><li>Once a Thread object is created, start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method − <strong>void start();</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6758982ab02f9a46d7e78ae24bd258a9/href">https://medium.com/media/6758982ab02f9a46d7e78ae24bd258a9/href</a></iframe><h3>Creating a Thread by extending the Thread Class</h3><ul><li>To create a thread, first make a new class that extends Thread, and then make an instance of it.</li><li>The extending class must override the <strong><em>run( )</em></strong> function, which serves as the new thread’s entry point.</li><li>Following is a simple syntax of run() method −<em> </em><strong><em>public void run( );</em></strong></li><li>It must also call <strong><em>start( ) </em></strong>to begin execution of the new thread.</li><li>Following is a simple syntax of start() method − <strong><em>void start( );</em></strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/affc62fd6eb7ec0029ca12909ab11b63/href">https://medium.com/media/affc62fd6eb7ec0029ca12909ab11b63/href</a></iframe><h4>isAlive( ) method</h4><ul><li>We can use the isAlive( ) method on a thread to see if it has ended.</li><li>Thread defines this technique, and its general form is as follows:</li></ul><p><em>final boolean isAlive( )</em></p><ul><li>The isAlive( ) function returns true if the thread that it is called on is still running. Otherwise, it returns false.</li></ul><h4>join() method</h4><p>If a thread wants to wait until completing some other thread, then we should go for join method.</p><p>For example: if a thread t1 wants to wait until completing thread t2 then t1 has to call t2.join(); If t1 executes t2.join() then immediately t1 will be entered into waiting state until t2 completes. Once t2 completes then t1 can continue its execution.</p><p>join method has following two forms:</p><p><em>— public final void join() throws InterruptedException;</em></p><p><em>— public final void join(long ms) throws InterruptedException ;</em></p><p><em>— public final void join(long ms, int ns) throws InterruptedException;</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5c296255ace6547cd83a47e4b259c19/href">https://medium.com/media/c5c296255ace6547cd83a47e4b259c19/href</a></iframe><h4>interrupt() method</h4><ul><li>A thread can use the interrupt() function of the Thread class to wake up a sleeping or waiting thread.</li><li>It’s general form is : <strong><em>public void interrupt()</em></strong></li><li>If the thread is neither sleeping or waiting, the interrupt() method behaves normally and does not interrupt the thread, but it does change the interrupt flag to true.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be7c77ed00088269c16b9ba65d567ef5/href">https://medium.com/media/be7c77ed00088269c16b9ba65d567ef5/href</a></iframe><h4>Thread Priorities</h4><ul><li>Every Java thread has a priority in Java. It could be a JVM-generated default priority or a programmer-defined priority.</li><li>Thread priorities can be between 1 and 10, with 1 being the lowest and 10 being the highest.</li><li>To indicate some standard priority, the Thread class defines the following constants:</li></ul><p>— Thread.MIN_PRIORITY = 1</p><p>— Thread.NORM_PRIORITY = 5</p><p>— Thread.MAX_PRIORITY =10</p><ul><li>Threads with a higher priority are more vital to a program and should be given priority over lower-priority threads when allocating processor time.</li><li>The thread scheduler, in most circumstances, arranges the threads according to their priority (known as preemptive scheduling).</li></ul><h4>setPriority() and getPriority() methods</h4><ul><li>Thread class defines the following methods to get and set priority of a thread:</li></ul><p><em>— public final int getPriority()</em></p><p><em>— public final void setPriority(int p)</em></p><ul><li>Here, p specifies the new priority setting for the calling thread. The valid range of p is within the range MIN_PRIORITY and MAX_PRIORITY.</li><li>We can obtain the current priority setting by calling the <strong><em>getPriority( )</em></strong> method.</li><li>To set a thread’s priority, use the <strong><em>setPriority( )</em></strong> method.</li><li>The default priority for main thread is 5 and for others default priority for other threads will be inherited from its parent. •</li><li>This method throws <strong><em>IllegalArgumentException </em></strong>if value of parameter level goes beyond minimum(1) and maximum(10) limit.</li></ul><h4><strong>yield() method</strong></h4><ul><li><strong>yield()</strong> causes the current thread to pause in order to make room for waiting threads with the same priority.</li><li>If no waiting threads exist or if all waiting threads have a low priority, the current thread can continue to run.</li><li>If numerous threads with the same priority are waiting, we have no way of knowing which one will receive the chance because it is determined by the thread scheduler.</li><li>The general form is: <strong>public static void yield()</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d262b5d500df6f1f51124814f63f15c/href">https://medium.com/media/2d262b5d500df6f1f51124814f63f15c/href</a></iframe><ul><li>If we comment out line ‘Thread.yield();’ in the above program, both threads will be executed at the same time, and we won’t be able to predict which thread will complete first.</li><li>If we don’t comment line’Thread.yield(); ‘, the main thread will have a higher chance of completing first.</li></ul><h4>Synchronization</h4><p>Synchronization in Java refers to the ability to govern different threads’ access to a shared resource.When two or more threads need access to a shared resource, they need a mechanism to guarantee that only one thread is using it at a time. Synchronization is the method by which this is accomplished.</p><p>When we only want one thread to access a shared resource, Java Synchronization is a better solution. Synchronization is primarily used to:</p><ul><li>Avoid thread interference;</li><li>Avoid consistency issues.</li></ul><p>Synchronization is based on a lock or monitor, which is an internal entity. A lock is associated with every object. By convention, a thread that requires consistent access to an object’s fields must first acquire the object’s lock, then release the lock after it’s finished.</p><h4>synchronized keyword</h4><ul><li>The synchronized modification only applies to methods and blocks, not classes or variables.</li><li>If many threads are attempting to operate on the same Java object, there is a risk of data inconsistency; to avoid this, we should use the synchronized keyword.</li><li>If a method or block is declared synchronized, only one thread at a time is allowed to execute that method or block on the supplied object, preventing data inconsistency.</li><li>The main benefit of the synchronized keyword is that it allows us to overcome data inconsistency issues, but the main disadvantage is that it increases thread waiting time and causes performance issues.</li><li>As a result, if there is no specified requirement, the synchronized keyword is not advised.</li></ul><p><strong>Synchronization</strong></p><ul><li>Every object in java has synchronized area and non-synchronized area.</li><li>The synchronized area can be accessed by only one thread a time, but non synchronized area can be accessed by any number of threads at a time.</li><li>The code where we do update actions like as add, delete, and update should be included in the synchronized section. That is, the status of the object changes.</li><li>The non-synchronized area includes actions like read that do not modify the state of an object.</li></ul><p>Synchronized Block</p><ul><li>The synchronized block can be used to perform synchronization on any of the method’s resources.</li><li>If method has 50 lines of code and just want to synchronize 5 of them, can use a synchronized block.</li><li>It will work the same as the synchronized method if place all of the method’s codes in the synchronized block.</li></ul><p>— Syntax</p><p><em>synchronized (object reference expression) {</em></p><p><em>//code block</em></p><p><em>}</em></p><h4><strong>wait() method:</strong></h4><ul><li>This function forces the current thread to release the lock and wait until another thread calls the notify() or notifyAll() methods on this object, or until a certain period of time has passed.</li><li>That is, when we call wait(), the current thread is forced to wait until another thread on the same object calls notify() or notifyAll().</li><li>The current thread must own this object’s monitor, so it must be called from the synchronized method only otherwise it will throw exception.</li><li>It has following three overloaded forms:</li></ul><p><em>public final void wait() throws;</em></p><p><em>InterruptedException public final native wait(long ms) throwsInterruptedException ;</em></p><p><em>public final wait(long ms, int ns) throws InterruptedException;</em></p><ul><li>The InterruptedException, which is a checked exception, is thrown by every wait() procedure.</li><li>As a result, whenever we use wait(), we must either use the try catch or throws keyword to handle the InterruptedException. Otherwise, a build time error will occur.</li></ul><h4>notify() and notifyAll() methods</h4><ul><li>notify() creates a single thread that is waiting on the monitor of this object.</li><li>If this object has any waiting threads, one of them is picked to be awakened.</li><li>The decision is arbitrary and made at the implementation’s discretion.</li><li>notifyAll() wakes up all threads waiting on the monitor of this object.</li><li>The forms of these methods:</li></ul><p><em>public final void notify()</em></p><p><em>public final native void notifyAll()</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e1a9e8a1e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hight Way Vehicle Passer]]></title>
            <link>https://chazool.medium.com/hight-way-vehicle-passer-c9efcd4743ad?source=rss-3b8f227f5d9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9efcd4743ad</guid>
            <dc:creator><![CDATA[Chazool]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 06:23:06 GMT</pubDate>
            <atom:updated>2021-06-07T06:23:06.679Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Background</strong></h3><p>Highways play an important and major role in making travelling easier and convenient. It enhances the transport system by reducing transport cost, travelling time by making transportation schedules and deliveries more timely and reliably. When it comes to the economy, highway transportation is really special and important. People who work in offices can report to their offices on time without any delay if they use a highway. Also huge numbers of companies are traveling goods; provide services in efficient and productive manner due to these highways. Other than economy highways families can also travel frequently there houses, go on trips or picnics with more ease. Even in these days ambulances also can use highways and patients can get emergency medicine and treatments due to these highways.</p><p>But in Sri Lanka sometimes we see there are large queues in highway exits. If there is a long weekend or if it is rush time to offices there are a large number of vehicles waiting in the queues in order to pay for the highway and to exit. So people are getting more time in queues so it’s useless using a highway if they stay so long in these queues. Main reason for this problem is that people use Manual Toll Collection (MTC) instead of Electronic Toll Collection (ETC).people always use traditional methods instead of using technologies. So by designing this application it will encourage people to use ETC rather than using MTC. In this highway vehicle passer system, there are some user attraction techniques and if people get used to these kinds of applications the above discussed problem will solve and we can get the maximum advantage from the highways too.</p><h3><strong>Problem</strong></h3><p>Under the circumstance of Covid-19, it is expeditiously spreading worldwide to a massive extent. In consequence people are guided to maintain social distance and for the most part, avoid interactions between each other. According to this situation, cash transactions between one another has become a considerable issue in this context. This pandemic can be spread effortlessly through cash transactions when exchanging currency notes.</p><p>Alternatively, The World Health Organization (WHO) advised the society to use several methods of transaction options for online payments. People have a good impression with these cashless solutions as these are swift and convenient to handle. Yet these cashless solutions such as cards and online payments are not implemented in vehicle parks and in highways. Usage of cash in these kind of locations are at a high risk of spreading this pandemic in a high rate</p><p>There are two main systems which can be utilized for transactions, Manual Toll Collection (MTC) and Electronic Toll Collection (ETC). ETC is very effective than MTC. But majorly people use this MTC method since it has no additional charge. Highways are compatible with Electronic Toll Collection System (ETC) payments. But for the ETC, people have to pay an installation fee for a unit. Due to these reasons and extra charges, people are reluctant to use this ETC method. Therefore, most of the vehicle owners are not using this method so the effectiveness of this system is very low. MTC is based on printing bills and it is not eco friendly due to that reason pollution of the environment is a considerable issue. ETC is based on electronic rays which can cause health problems in the human body.</p><p>As per the current ETC payment method, vehicles are charged for the toll but the card cannot be recharged through online and also if the vehicle does not have an ETC Master card this method is useless. Besides, there is no appropriate mechanism to measure the time that vehicles spend in service areas or fuel stations inside the highway. Crucially there is no one appropriate solution to track the time spent and the expenditures made while traveling on a highway, equally public and the government face problems in assembling information and statistics.</p><p><strong>Examples</strong></p><ul><li>Tracking the time, when a person arrives and departures a supermarket and the expenses made.</li><li>Identifying publics who use automated bill payment technologies at public places.</li><li>Tracing the procedure time period of public transportation.</li><li>Identifying people who cooperated with public places as hospitals or restaurants.</li></ul><h3><strong>Solution</strong></h3><p>When analyzing the present condition, it was possible to recognize the appropriateness of an online system. By Creating of this system, it will become more effective and efficient moreover, expecting to provide an efficient service. The web app allows users to log in, and anyone with a driving license can register and use it. It has the capability to register and use public vehicles separately. When finalizing the registration, the customer obtains an authorization email and is able to get the relevant barcode from a particular place. Essentially it is possible to organize an appropriate method to top-up those cards online or any place in the country.</p><p>Through this app, the public have the ability to register their vehicles and customize which vehicle to use in this circumstance before entering the highway and also if a client using someone else’s vehicle for travel, it is possible to enter and use the ID of that following vehicle. If ETC cardholder is facing any problem regarding the ETC card or if anyone registered for ETC card have the ability to settle the payments and it varies up to the ability that can pay. Unlike ETC, this is not including any installation fee and registration is completely free of charge. There is a tendency for the majority of people to be interested towards this.</p><p>When it is required to make a payment, public can tap the card with the barcode included on the barcode reader at the highway entrance or they can start the journey by scanning the QR code installed on the following app. In-between the drive, if a customer enters the service area they can read the barcode or scan the QR code at the following locations and in exit too. Afterwards they can do the way as mentioned above. The travel fee will be charged from the user’s account and the bill will be receiving via e-mail. This procedure can stop the destruction caused by the bills printed by the MTC and cease the damage caused to the bodies by the electronic waves radiated by the ETC.</p><p>With this application, it can effortlessly record the information of drivers as well as the entrances and the departures of the vehicles. Besides, if they arrived the service areas it can easily classify the places they have stayed and the time spent at those several areas. If an individual infected with Covid-19, it can easily identify and treat people and also who have been in and out of the area for specified period of time, from the time of entry to the time of departs along with the people got engaged with the infector.</p><h4><strong>System functionalities</strong></h4><h4>Home</h4><p>If it is a new user, the following user can go through the registration button and create a new own account and if a person already owned an account, user can log in to the system through the login button and use it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*m0JH8lrUlUvYWY5vO2hLew.png" /></figure><h4><strong>Registration</strong></h4><p>This allows a new user to create their own account by entering their own data and once the account created, the registration will be verified by email That following email consist with the numbers connected to their barcode card has also been stated. They have to send the number code to the appropriate place and get the barcode card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*CgBlz7jSxrXlmtmcSINQZw.png" /></figure><h4><strong>Login</strong></h4><p>This is the login page for all types of users to login. Any user can enter the system by entering their username and password. If they entered a wrong username or password, it will be displayed as an error. After entering the correct user details, user have the access to the dashboard corresponding to that user type and the dashboard is displayed as given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*QWje3W_8935o5MpfUCBiCg.png" /></figure><h4><strong>Dashboard</strong></h4><p>As mentioned above, the dashboard related to the user type of the logged in user will look as given below.</p><ul><li><strong><em>Driver Dashboard</em></strong></li></ul><p>This is the dashboard that appears when “driver” is the user type. It shows the account balance of the driver, and current active vehicles and detail etc. The user can click on the “ADD VEHICLE” button and add other vehicles to the system. The “ACTIVE VEHICLE” button can use to change the current active vehicle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*cR4_vQfpxol31VeslmI11g.png" /></figure><ul><li><strong><em>Operator Dashboard</em></strong></li></ul><p>This is the dashboard appears when the user type operated. The chart appeared shows the full recharged amount for the previous six days including the current day. With the “RECHARGE” button, user can log to the recharge page of the driver’s account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_sO4yiYSROplQFjU3vkcw.png" /></figure><ul><li><strong>Admin Dashboard</strong></li></ul><p>This is the dashboard appears when the user type is admin. The chart given below shows the entrance and exit vehicle count for the present day and previous six days. The next chart illustrates the entrance vehicle type count and the final chart shows the exit vehicle type count. All those charts can be changed according to the location. “TERMINAL CONTROL” button let the users log to the page used to control the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNWYvrhI2n9s2rmZovji1g.png" /></figure><h4><strong>Profile</strong></h4><p>This page can be only used for Drivers. It can edit and update all the information of the driver. It will be notified by email and a popup alert after the update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*jhusNlSsATc1GgDqmkXIJw.png" /></figure><h4><strong>Add Vehicle</strong></h4><p>This is used to alternate the driver’s vehicle into an active vehicle. By entering the vehicle ID, it can confirm the active vehicle for the journey. After changing the vehicle, it will be notified by an e-mail and a popup alert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*AVgUZFClBPJrykKnGDvnTw.png" /></figure><h4><strong>Recharge</strong></h4><p>This can be only used for operator type users. This permits to recharge the driver’s account. After the account recharged, the driver will be notified via an e-mail and the operator with a popup alert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pN6h8KKh2M-XmtNVvcMMZw.png" /></figure><h4><strong>Terminal control</strong></h4><p>This is only customized for admin type users. This permit to open a vehicle portal for entrance and exit. The portal capable to read the driver’s barcode and allow to enter and exit. At the time of entrance, the system will check whether the account is less than thousand rupees and if it is less than thousand, it will be notified via a pop-up alert. After reading the portal card in entrance or exit, driver will be notified via email and the screen too notified via pop-up. The amount related to the journey will be notified in exit via e-mail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfPYxdXOGoTxM0TtTky7fA.png" /></figure><h4><strong>Futures Enhancement</strong></h4><p>The following functions will be added in future versions.</p><ul><li>If the password is forgotten or it need to be changed, the system expected to be updated so that can be changed.</li><li>The table in “ADD VEHICLE” is expected to facilitate the activation of a vehicle easily.</li><li>If the driver’s barcode is misplaced, expecting to add a new feature that allows the system to request and activate the card as well as allow to request a new card.</li><li>When the driver’s account being recharged, it is possible to link the credit or debit cards and planning to update the payments to pay automatically when they travel through highway.</li><li>Expecting to add a feature for the drivers to view the recharge history, travel history, and payment history.</li><li>Planning to create a recharge report that can be obtain location wise and user wise for operators.</li><li>In addition to e-mails, expecting to activate SMS alert service</li><li>Hope to create the user interfaces attractive and user friendly.</li></ul><h3><strong>Identified Problems in the Current System</strong></h3><ul><li>The current system is a web application therefore; it is difficult to use a browser. The users have to remember the web addresses every time and enter those accurately. Due to that, users facing many difficulties in this procedure. The user login page is the default login page in OAuth so every error message that appears on it is irreplaceable and not user friendly.</li><li>The card used for the driver is a car with a barcode and must be held in the correct position when reading if it is not so, no reading will take place. In case of service down, page not found, an error appears on the browser as it is a bad experience for user. The user will not be able to use the system again and again and the messages appearing there are not user friendly.</li><li>Presently, the log history does not create a history of backend processes in the system to identify how a system error occurred.</li><li>The ETC allows the vehicle to travel without stopping and this system requires the vehicle to be stopped and scanned. Therefore, the driver may express an unwillingness to do more work.</li><li>Even though created an API gateway still requests have been calling through frontend to directly backend HTTP request that means requests are not going through API gateway. So restrictions, validations and etc. cannot be done.</li><li>When considering these system integrations problems, the main focus is on the User Interfaces. Lack of responsiveness of some components and pages can be seen as a major problem. Moreover, the icons and components used for that should be designed to be more beautiful, simple and attractive. Using the same components, color matching, icons and images are features of a good system.</li><li>In this application notifications are sending only through emails neither SMS or any other notification method. Therefore driver always needs to login to his/her email in order to view notifications</li><li>Even a stranger who knows the username and password can login and use the system. There are no further security restrictions for this, so it is possible that it can easily transfer the user account to someone else</li></ul><h3><strong>Mitigation for the identified problem</strong></h3><ul><li>can create a custom login page for the login page and connect “OAuth” to it. can display more custom messages such as “user not exit”, “invalid password” Or can use the JWT Token for a token validation. Actually, JWT is a self contained token which has authentication information, expiration time information, and other user defined claims digitally signed. No Cookies Required, Thus It’s Very Mobile Friendly. Token can be generated anywhere. Also, the authentication can happen on the resource server or it is easily separated into its own server.</li><li>Login services like log4j, logbash can be used to create a log file. System admin can identify how it happened even when the system went down. And a log manager like elastic Kibana is very easy to use. Because Kibana is data querying &amp; analysis. In addition, Kibana’s visualization features allow to see data in alternate ways using heat maps, line graphs, histograms, pie charts, and geospatial support. With various methods, search the information stored in Elasticsearch for root cause diagnostics.</li><li>Instead of the current barcode card, the app can use a QR scanner with an NFC card. Nobody enjoys waiting in long lines. NFC technology makes it easier than ever to accept payments quickly. Customers tap their NFC enabled credit card on the payment device and that’s it. won’t have to hand over a card even if they use it to pay for services. Simply tap the card on the payment device, and the transaction is complete. They simply waive their phone above the payment device and that transaction is complete. Limiting customer contact means reducing the spread of germs.</li><li>It’s the page that crops up when all else fails, appearing to encounter a broken link, make a spelling mistake within the web address, or happen to enter during a website’s maintenance. albeit they shouldn’t ideally be viewed. A quick note explaining there’s been a mistake . Readers got to see immediately that they’re not where they think they’re . An evidence of why this went on . The foremost common reasons are a typo or broken link, but attempt to not make it sound like blaming the user. ‘Something went wrong’ may be a much more neutral statement than done something wrong. A navigation bar. There’s nothing more irritating than a mistake page that has no options for moving onwards, so keep the main navigational elements to permit people to undertake elsewhere . It’s important to make it as easy as possible for them to remain on the location — at the moment , they’ll be frustrated and tempted to go away.</li><li>can increase security and restrictions by talking from the frontend to the backend through the gateway. It is best to use a Zuul gateway. It manages all the requests and performs the dynamic routing of microservice applications. It works as a front entrance for all the requests. It’s also referred to as Edge Server. Identifying authentication requirements for every resource and rejecting requests that don’t satisfy them. Tracking meaningful data and statistics at the sting so as to offer us an accurate view of production. Allocating capacity for every sort of request and dropping requests that re-evaluate the limit.</li><li>It is difficult for a driver who is not logged in for email to receive messages only from emails. Therefore SMS and notification can be used. Companies that have a text messaging alert system are ready to save time with the utilization of the said technology. By sending text messages, firms can promote their services quickly and efficiently. Push notifications are basically alerts users receive in real-time from a mobile app and which slide in as a banner on their screen. These sorts of mobile app notifications are the simplest way for companies and marketers to speak with their users, but if not through with a careful strategy in place , push notifications can annoy users and cause them to drop the app completely.</li><li>Although the current UI of the system is created by bootstrap, it is suitable to test by other phone tabs or similar emulators from the browser to minimize the loss of responsiveness on certain pages. It is easy to create and reuse the systems by using frontend languages such as react or angular for the frontend development. When load balancing, can prioritize the components that should appear first. It is better to do things like UI and UX for icon on the advice of an expert.</li><li>It’s very easy for users having android and IOS mobile applications other than a web application. To create such applications, can use the backend currently having. The iOS application and the android application can be created separately but can be used a cross platform language. It allows developers to create mobile apps that run on multiple OS’s by using a single framework and sharing the same code base. The framework modifies businesses to build native-like experiences by reducing the development effort and costs while speeding up the time-to-market.</li><li>In addition to username and password, it is better to use two factor authentication. Passwords are old-fashioned and will be phased out. As everyone knows, users fall time and again into the bad habit of selecting weak passwords. Analyses of hacked passwords regularly show that enormous proportions of individuals choose passwords like ‘123456’ and ‘password’, with requirements for alphanumeric passwords scarcely improving things . There utilized in combination with a password, 2FA greatly increases security. A better approach is to urge obviate passwords all at once . 2FA delivers an additional layer of protection for user accounts that, while not impregnable, significantly decreases the danger of unauthorized access and system breaches.</li></ul><h3><strong>Technical Design</strong></h3><p>Technology was one of the main factors in the creation of this system. What is the new technology and how to apply it to this problem domain was considered next. Created by studying how to use new technology.</p><h4>Technology</h4><ul><li>Java 8</li><li>Spring Boot</li><li>Bootstrap</li><li>JavaScript</li><li>Mysql</li><li>Docker</li></ul><p><strong>Benefit of Selected Technologies</strong></p><p><strong>Java 8</strong></p><ul><li>Java language offers higher cross-functionality and convenience as Software written in one stage can run areas, mobiles, inserted frameworks.</li><li>its object-oriented, working multithreading ,distributed ,and network support</li><li>The Java Class Library enables cross-platform development.</li><li>developers to write high quality code and help maintain its competitiveness among other programming languages.</li></ul><p><strong>Spring Boot</strong></p><ul><li>Actually, It is very easy to develop Spring Based applications with Java.</li><li>Reduces lots of development time and increases productivity.</li><li>And, the Java is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.</li><li>This give “Opinionated Defaults Configuration” Approach to reduce Developer effort</li><li>This provides Embedded HTTP servers like Tomcat, Jetty etc. for develop and test our web applications very easily.</li><li>Further, Spring gives lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and Gradle</li></ul><p><strong>Bootstrap</strong></p><ul><li>By Using Bootstrap, save a lot of time. Specially, no need to spend time writing code, simply use the Bootstrap predefined configuration layouts and classes and put it precisely where they fit.</li><li>Also, this offers many ways to be customized so that can make it own. It can pick and choose what is needed and toss what is not. Further, Bootstrap can be adjusted exactly as you want it and as your project requires.</li><li>Bootstrap Can Create mobile-ready websites is a breeze with Bootstrap thanks to the fluid grid layout that dynamically adjusts to the proper screen resolution.</li><li>Not that, it is compatible with all modern browsers and Internet Explorer versions.</li></ul><p><strong>JavaScript</strong></p><ul><li>JavaScript is a client-side scripting language for the web page.</li><li>It Increases the interactivity and usability of the web page.</li><li>This make the web page more user-friendly by providing easy to use and rich features.</li><li>It saves server traffic by validating user input before sending to the server.</li><li>JavaScript respond immediately if there is any mistake in user data without waiting for the page reload.</li></ul><p><strong>MySql</strong></p><ul><li>It is a Relational Database Management System (RDBMS) which means that it stores and presents data in tabular form, organized in rows and columns.</li><li>It consists of a solid data security layer to protect sensitive data from intruders and passwords in MySQL are encrypted.</li><li>This is available for free to download and use from the official site of MySQL.</li><li>Compatible with most of the operating systems, including Windows, Linux, NetWare, Novell, Solaris and other variations of UNIX.</li><li>Can build and interact with MySQL with only the basic knowledge of MySQL and a few simple SQL statements.</li><li>Scalable and capable of handling more than 50 million rows. It’s enough to handle almost any amount of data. However, the default file size limit is 4GB but it can be increased to 8TB</li></ul><p><strong>Docker</strong></p><ul><li>It brings in an API for container management, an image format and a possibility to use a remote registry for sharing containers.</li><li>Docker containers contain the minimal runtime requirements of the application, reducing their size and allowing them to be deployed quickly.</li><li>Docker container can be transferred to another machine that runs Docker, and executed there without compatibility issues.</li><li>Docker containers reuse components from the preceding layers, which makes them noticeably lightweight.</li><li>Docker images are typically very small, which facilitates rapid delivery and reduces the time to deploy new application containers.</li><li>Decreases effort and risk of problems with application dependencies.</li></ul><h4>Application of Technologies.</h4><p>Able to create this system using the above technology. The microservice architecture was used there. A docker was used for the deployment.</p><p>Here, the fundamental thought behind a microservice design is that applications are less complex to make when weakened into smaller pieces that perform seamlessly together. Separate programming functionality into multiple independent modules that are individually liable for performing precisely defined, standalone tasks, when using microservices. There, those modules communicate with each other through simple, generally available application programming interfaces (APIs).</p><ul><li>They are divided into various particular, loosely coupled components, every one of which performs a discrete function</li><li>Individual functions built to align to business capabilities</li><li>Distributed across clouds and data centers</li><li>Treat each function as an independent service which will be changed, updated, or deleted without disrupting the remainder of the appliance</li></ul><h3><strong>Architecture of the application</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNoSOimVxcaOM8f9-UDFzQ.png" /><figcaption><strong>Architecture Diagram</strong></figcaption></figure><p>This is the Architecture in this system. This gives an idea of the whole system. How the system works. This diagram is based on the micro service architecture. Hope to describe below how the diagram works. In addition, how the system was developed and hope to put the relevant sample code.</p><p>As an application moves through the deployment pipeline from dev to check and into production, it can deal with the configuration between those environments and be sure that applications have everything they have to run once they migrate.</p><h4>Configuration Server</h4><p>Spring Cloud Configuration Server can be a centralized application that deals all the appliance related configuration properties. the thought is that programs can move Configuration to an external place so this application is definitely configurable and may even change their settings. to try to do this, create a configuration server and a client that reads your configuration of that server. The configuration server uses a GIT repository on GitHub, where it stores the configuration files</p><p>As an application moves through the deployment pipeline from dev to check and into production, it can manage the configuration between those environments and be sure that applications have everything they have to run once they migrate.</p><ul><li><strong>Spring Cloud Config Server</strong></li></ul><p>Can build it as a Spring Boot application that depends on spring-cloud-config-server to use these features in an application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97423dd10049ac463be3cc64d4e89be8/href">https://medium.com/media/97423dd10049ac463be3cc64d4e89be8/href</a></iframe><p>The Configuration Server is embeddable during a Spring Boot application, by using the @EnableConfigServer annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a2bf0ec1f90d1b63e6bf2e4068432c7/href">https://medium.com/media/0a2bf0ec1f90d1b63e6bf2e4068432c7/href</a></iframe><p>Git repository containing bootstrap.yml file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efe904559dfc58ee070372ff4434c6a5/href">https://medium.com/media/efe904559dfc58ee070372ff4434c6a5/href</a></iframe><ul><li><strong>Spring Cloud Config Client</strong></li></ul><p>Once the configuration server works, create the client. add this dependency to pom.xml file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b706c1db12b463ed75704d36f6591ff9/href">https://medium.com/media/b706c1db12b463ed75704d36f6591ff9/href</a></iframe><p>In addition to the appliance name, also put the active profile and therefore the connection-details in bootstrap.yml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3028b96f7bdaa63d2b740404cabeb09/href">https://medium.com/media/f3028b96f7bdaa63d2b740404cabeb09/href</a></iframe><h4><strong>Netflix Eureka Discovery</strong></h4><p>This is provided by Netflix. It consists of the Eureka Discovery Server and Eureka Discovery clients. Every Micro service will register into the invention server and Discovery server knows all the client applications running on each port and IP address.</p><p>When making a REST call to a different service, rather than providing a hostname and port, they only provide the service name.</p><ul><li><strong>Eureka Discovery Server</strong></li></ul><p>This is the Eureka Server, and for that, include a Eureka dependency in the project. Below is the pom.xml for Eureka Discovery Server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab006c587aa38cfe32a51392185fc1fe/href">https://medium.com/media/ab006c587aa38cfe32a51392185fc1fe/href</a></iframe><p>Also, update the application.yml file for this project to indicate that it is a discovery server and not a client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebd086cbdf7a9dbc523cc33002c0a442/href">https://medium.com/media/ebd086cbdf7a9dbc523cc33002c0a442/href</a></iframe><p><em>To make a Eureka Discovery server, add the @EnableEurekaServer annotation to main class</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b1b0e903163c267d91455b212b60f65/href">https://medium.com/media/6b1b0e903163c267d91455b212b60f65/href</a></iframe><ul><li><strong>Eureka Discovery Client</strong></li></ul><p>created other microservices with Spring Boot and every one running on its own port or Port 0.</p><p>add this dependency to pom.xml file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf15e1e3f6c07ec22fb610133143ee7e/href">https://medium.com/media/cf15e1e3f6c07ec22fb610133143ee7e/href</a></iframe><p>As a client, it should register itself to the server, which happens within the application.yml file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e134b268b8f8a207eabd604f00a2aec8/href">https://medium.com/media/e134b268b8f8a207eabd604f00a2aec8/href</a></iframe><p>To make a Eureka Discovery client, all we’d like to try to to is add the @EnableEurekaClient annotation to main class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4542457bd4762ecce8e9aae7cbc813a/href">https://medium.com/media/c4542457bd4762ecce8e9aae7cbc813a/href</a></iframe><h4><strong>Authentication server</strong></h4><p>When building a web application, authentication and authorization is a must. Authorization Server is a supreme architectural component for Web API Security. The Authorization Server acts as a centralization authorization point that allows HTTP endpoints to identify the features of the application. Also in this server it is handling the user and user types. build an OAuth 2.0 web application and authentication server using Spring Boot and Spring Security.</p><p>Regarding security , two main areas are identified:</p><p>Authentication — Confirms users are who they say they are.</p><p>Authorization — Give users permission to access a resource.</p><p>In this application, there are 3 types of different user categories. They are driver, operator and admin. These three user categories have different access privileges and according to these user categories and privileges each account will handle.</p><p><strong>Oauth Server</strong></p><p>OAuth2 is an authorization framework that enables the application Web Security to access the resources from the client. application, need to focus on the Grant Type, Client ID and Client secret.</p><p>This is the Auth Server, and for that, include oauth2 and security dependencies in the project. Below is the pom.xml for Auth Server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f27973bfe48b3ae67c149f49a5626672/href">https://medium.com/media/f27973bfe48b3ae67c149f49a5626672/href</a></iframe><p>Also,update the application.yml file for this to define the minimal required configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fda7c254acb8d2915e53b916c3fbb085/href">https://medium.com/media/fda7c254acb8d2915e53b916c3fbb085/href</a></iframe><p><em>To make a Auth server, add the @EnableAuthorizationServer annotation to main class</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/478b3f6bf8383741eb8e5b6ad5cea0df/href">https://medium.com/media/478b3f6bf8383741eb8e5b6ad5cea0df/href</a></iframe><p><em>Configuration class enables and configures an OAuth authorization server.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14df27a63fb5598921678524a60539fd/href">https://medium.com/media/14df27a63fb5598921678524a60539fd/href</a></iframe><p><strong>Oauth Client</strong></p><p>Rest-Api client services that fetch the from the resource server. Used these dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/901be797971341e89517f2128007bf51/href">https://medium.com/media/901be797971341e89517f2128007bf51/href</a></iframe><p>Also, update the application.yml file for this to define the minimal required configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/603497788a8343fe00d42f2ab4788309/href">https://medium.com/media/603497788a8343fe00d42f2ab4788309/href</a></iframe><p><em>To make a Auth Client, add the @EnableResourceServer annotation to main class</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/679b632a0d1b62cb356e6d160e973d0a/href">https://medium.com/media/679b632a0d1b62cb356e6d160e973d0a/href</a></iframe><h4><strong>Gateway</strong></h4><p>An API gateway is programming that sits in front of an API and is the single-entry point for defined back-end APIs and microservices. It might have other responsibilities such as authentication, monitoring, load balancing, caching, request shaping and management, and static response handling</p><ul><li><strong>Zuul Gateway</strong></li></ul><p>Zuul is provided by Netflix. Spring Boot has already bundled Zuul with their Spring Cloud dependency.</p><p>As an edge service application,Zuul is designed to enable dynamic routing, observing, flexibility and security.</p><p>This is the Zuul Cloud API Gateway, and for that, include Zuul Server dependencies in the project. Below is the pom.xml for gateway.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9222a70684f0504e2630111df01ad4de/href">https://medium.com/media/9222a70684f0504e2630111df01ad4de/href</a></iframe><p><em>To make a Auth server, add the @EnableZuulProxy annotation to main class</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e2ce2f7fcca3f5dcb1b31ef530690c0/href">https://medium.com/media/9e2ce2f7fcca3f5dcb1b31ef530690c0/href</a></iframe><p>defined configuration properties for gateway purposes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65d0cac4a8afed0bb8c1fb1e8abdec9e/href">https://medium.com/media/65d0cac4a8afed0bb8c1fb1e8abdec9e/href</a></iframe><h4><strong>servicers</strong></h4><p>According to the problem domain, Rest API is divided into four different services. They are; Driver service, email service, Transaction service and Payment service.</p><ul><li><strong>Driver Service</strong></li></ul><p>If a driver is using this application, he/she needs to should register with the system along with</p><p>their details. Also, driver can pay highway fee by his/her own without using vehicle owners’</p><p>card. Also, drivers should use a card while entering the highway.</p><ul><li><strong>Transaction Service</strong></li></ul><p>Save entering point and exciting point in order to identify and also can use this to send emails</p><p>to the owner of the vehicle and as well as the driver of the vehicle.</p><ul><li><strong>Payment Service</strong></li></ul><p>As mentioned above, drivers can pay his/her by own. Driver can handle multiple payment</p><p>methods. I.e. he can use a System Card for the payment process.</p><ul><li><strong>Email Service</strong></li></ul><p>Vehicle owners and drivers will receive emails while entering and exiting the highway. Also,</p><p>the driver will receive an email after the payment by including payment information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9efcd4743ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>