<?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 Naveen Raju on Medium]]></title>
        <description><![CDATA[Stories by Naveen Raju on Medium]]></description>
        <link>https://medium.com/@nnaveenraju?source=rss-180ff554c744------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sknpwMRMdzy0LCkSjr6Kxw.jpeg</url>
            <title>Stories by Naveen Raju on Medium</title>
            <link>https://medium.com/@nnaveenraju?source=rss-180ff554c744------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:34:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nnaveenraju/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[Claude Code… Status Line Metrics]]></title>
            <link>https://medium.com/naveen-blog/claude-code-status-line-metrics-c8b1b8a936bd?source=rss-180ff554c744------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8b1b8a936bd</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[free-claude-code]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[claude-code-tips]]></category>
            <dc:creator><![CDATA[Naveen Raju]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 13:29:33 GMT</pubDate>
            <atom:updated>2026-02-14T12:46:21.162Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a Smarter Claude Code Statusline (With Costs and Suggestions)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FogQM7fGBt4U4DG4g3hRQ.png" /></figure><h3>I Built a Real-Time Dashboard Into Claude Code’s Status Line (And It Uses Data You Didn’t Know Existed)</h3><p><strong>TL;DR</strong>: Claude Code sends a rich JSON payload to custom statusline scripts on every interaction — — actual cost, context usage, session duration, token counts, and more. I built a ~400 line bash script that turns this into a live dashboard showing everything you need to make smart decisions about pacing, context management, and parallel sessions.</p><h3>The Problem: Flying Blind</h3><p>My workflow with Claude Code isn’t one terminal, one task. It’s multiple terminals, multiple projects, all sharing the same Anthropic account. Each instance burns tokens independently, but the rate limit is shared.</p><p>I couldn’t see:</p><ul><li>How much I was spending <em>right now</em> (not after the fact)</li><li>How fast my context window was filling — — and when auto-compaction would wipe my conversation state</li><li>Whether my tools were failing silently in retry loops</li><li>What my <em>actual</em> aggregate burn rate was across all sessions</li></ul><p>I needed a status line. Not a separate monitoring tool, not a browser tab, not a TUI — — something <em>inside</em> Claude Code that updates on every interaction.</p><h3>The Insight: Claude Code Sends You Everything</h3><p>Here’s what most people don’t realize: Claude Code’s statusline hook doesn’t just call your script — — it <strong>pipes a JSON payload via stdin</strong> containing the current session’s actual metrics. Cost, context, duration, model, token breakdown — — all of it. No estimation needed.</p><pre>{<br>  &quot;session_id&quot;: &quot;420c9207-5fd1-4456-abd0-e14456ee16ba&quot;,<br>  &quot;transcript_path&quot;: &quot;/Users/naveen/.claude/projects/.../420c9207.jsonl&quot;,<br>  &quot;model&quot;: {&quot;id&quot;: &quot;claude-opus-4-6&quot;, &quot;display_name&quot;: &quot;Opus 4.6&quot;},<br>  &quot;version&quot;: &quot;2.1.39&quot;,<br>  &quot;cost&quot;: {<br>    &quot;total_cost_usd&quot;: 3.56,<br>    &quot;total_duration_ms&quot;: 1472713,<br>    &quot;total_api_duration_ms&quot;: 772588,<br>    &quot;total_lines_added&quot;: 306,<br>    &quot;total_lines_removed&quot;: 554<br>  },<br>  &quot;context_window&quot;: {<br>    &quot;total_input_tokens&quot;: 20147,<br>    &quot;total_output_tokens&quot;: 42321,<br>    &quot;context_window_size&quot;: 200000,<br>    &quot;current_usage&quot;: {<br>      &quot;input_tokens&quot;: 3,<br>      &quot;output_tokens&quot;: 9,<br>      &quot;cache_creation_input_tokens&quot;: 4,<br>      &quot;cache_read_input_tokens&quot;: 43791<br>    },<br>    &quot;used_percentage&quot;: 22,<br>    &quot;remaining_percentage&quot;: 78<br>  }<br>}</pre><p>That cost.total_cost_usd is the real number --- not an estimate from a pricing table. The context_window.used_percentage is Claude&#39;s own calculation. No guessing.</p><p>The previous version of this script estimated cost by parsing JSONL session files and multiplying token counts by model-specific rates. It worked, but it was always approximate. Now? The source of truth comes straight from Claude Code.</p><p>JSONL files (at ~/.claude/projects/&lt;project-dir&gt;/&lt;session-id&gt;.jsonl) are still useful for one thing: <strong>tool and message stats</strong>. Claude&#39;s native JSON doesn&#39;t include tool breakdowns, so the script parses the session transcript for those.</p><h3>What I Built: 9 Lines of Real-Time Intelligence</h3><p>Claude Code supports a custom status line via settings.json. Point it at a shell script, and it renders the output below your prompt on every interaction. Here&#39;s what mine looks like:</p><pre>📁 ~/my-project  🤖 Opus 4.6  📟 2.1.39  🌿 main*(+2~3?1)<br>🧠 Context: 43.8K/200.0K (22%) • Until compact: 1h 27m ▓▓░░░░░░░░<br>💰 $3.56 ($8.70/hr) • In:20.1K Out:42.3K Cache:43.8K<br>⏱️  Session: 0h 24m (API: 12m 52s) • Cache: 99%<br>📊 62.5K tok • 💬 18 msgs • 🔧 R:12 E:5 B:8 W:2<br>📂 4 files • ⚡ 1.8K/min • ✅ 98% tools • 📝 +306/-554 lines<br>📈 Peak: 43.8K<br>✅ All good</pre><p>At a glance, I know <em>exactly</em> where I stand. Let me walk through what each line does and why it matters.</p><h3>Line by Line: What You’re Looking At</h3><h3>Line 1 — — Session Context</h3><pre>📁 ~/my-project  🤖 Opus 4.6  📟 2.1.39  🌿 main*(+2~3?1)</pre><p>The basics: where you are, which model is running (this directly affects pricing), your CLI version, and your git state. The dirty indicators are compact but information-dense:</p><ul><li>+2 = 2 files staged</li><li>~3 = 3 files modified but unstaged</li><li>?1 = 1 untracked file</li><li>* = uncommitted changes exist</li></ul><p>Why include git? Because I’ve kicked off expensive Claude operations on the wrong branch more times than I’d like to admit.</p><h3>Line 2 — — Context Window &amp; Compaction Countdown</h3><pre>🧠 Context: 43.8K/200.0K (22%) • Until compact: 1h 27m ▓▓░░░░░░░░</pre><p>This is the line that changed how I work. Claude Code has a 200K token context window. When it fills, auto-compaction fires — — the conversation gets summarized, detail is lost, and you burn extra tokens in the process.</p><p>The “Until compact” timer calculates <em>context velocity</em> (tokens consumed per minute based on your session history) and projects when you’ll hit the wall:</p><pre>context_velocity=$(( actual_context_tokens * 60 / session_elapsed ))<br>tokens_remaining=$(( MAX_CONTEXT - actual_context_tokens ))<br>minutes_to_full=$(( tokens_remaining / context_velocity ))</pre><p>When this says 12m, I know to run /compact proactively rather than letting Claude do it mid-task and lose important context.</p><h3>Line 3 — — Cost &amp; Token Breakdown</h3><pre>💰 $3.56 ($8.70/hr) • In:20.1K Out:42.3K Cache:43.8K</pre><p>The cost is <strong>actual</strong> — — pulled directly from cost.total_cost_usd in Claude Code&#39;s native JSON. No pricing tables, no estimation. The hourly rate is calculated from the real cost and session wall time.</p><p>The token breakdown shows cumulative session totals: input tokens, output tokens, and cache read tokens. This tells you <em>where</em> the tokens are going. A high Cache number relative to Input means prompt caching is working well.</p><pre>calc_cost=$(n cost_usd &quot;0&quot;)  # Actual cost from Claude Code<br>cost_per_hour=$(echo &quot;scale=2; $calc_cost / $session_hours&quot; | bc)</pre><h3>Line 4 — — Session Timing &amp; Cache Efficiency</h3><pre>⏱️  Session: 0h 24m (API: 12m 52s) • Cache: 99%</pre><p>Wall clock time vs. actual API time. In this example, the session is 24 minutes old but Claude spent 12m 52s of that on API calls. The rest is you reading output, thinking, and typing.</p><p>The cache hit rate shows what percentage of your prompt tokens were served from cache vs. sent fresh. Higher = faster responses and lower cost per interaction. Both timing values come from Claude Code’s native total_duration_ms and total_api_duration_ms.</p><h3>Line 5 — — Token &amp; Tool Analytics</h3><pre>📊 62.5K tok • 💬 18 msgs • 🔧 R:12 E:5 B:8 W:2</pre><p>Total token consumption, conversation length, and a tool usage breakdown:</p><ul><li><strong>R</strong> = Read (file reads)</li><li><strong>E</strong> = Edit (file modifications)</li><li><strong>B</strong> = Bash (shell commands)</li><li><strong>W</strong> = Write (new file creation)</li></ul><p>This breakdown is surprisingly useful. If I see B:47 and the session is only 20 minutes old, something is probably in a retry loop. If W:12 is high, I&#39;m generating a lot of new files and should check nothing was duplicated. These stats come from parsing the session JSONL file --- the one metric that still requires file parsing.</p><h3>Line 6 — — Activity &amp; Code Impact</h3><pre>📂 4 files • ⚡ 1.8K/min • ✅ 98% tools • 📝 +306/-554 lines</pre><p>Files touched (unique files edited or written), context velocity (how fast tokens are being consumed — — your “speedometer”), tool success rate (calculated from tool_use_error counts in the session log), and lines of code changed (from Claude Code&#39;s native total_lines_added / total_lines_removed).</p><p>The tool success rate is an early warning. If it drops below 90%, the status message changes to flag it:</p><pre>if [ &quot;$tool_success_rate&quot; -lt 90 ]; then<br>  status_msg=&quot;⚠️ ${tool_success_rate}% tool success — Errors may be causing retries, check output&quot;<br>fi</pre><h3>Line 7 — — Peak Context &amp; Compaction History</h3><pre>📈 Peak: 43.8K • 🔄 2x compact</pre><p>Peak context tracks the highest context window usage during the session — — persisted across compactions in a state file. The compaction counter detects when context drops by 50%+ (the signature of auto-compaction):</p><pre>if [ &quot;$actual_context_tokens&quot; -lt $(( LAST_CONTEXT_TOKENS / 2 )) ]; then<br>  COMPACTION_COUNT=$(( ${COMPACTION_COUNT:-0} + 1 ))<br>fi</pre><p>On heavy sessions I’ve seen 🔄 138x compact. That number is a wake-up call about how much context you&#39;re churning through.</p><h3>Line 8 — — Multi-Session Awareness (Conditional)</h3><pre>🌐 +2 other session(s): $8.45 (650.2K tok) • $12.30/hr</pre><p>This line <strong>only appears</strong> when other Claude Code sessions are actively running (any session JSONL file modified in the last 5 minutes, excluding your current session). It sums costs and tokens across every other active instance.</p><p><strong>Why 5 minutes instead of 60?</strong> Active sessions write to their JSONL file on every interaction, so a 5-minute window catches real concurrent sessions without false positives from old session files that happened to be touched recently. And by excluding the current session, you’ll never see “1 session running” — — you already know about your own.</p><pre># Exclude current session, only count others modified in last 5 min<br>while IFS= read -r sf; do<br>  sf_base=$(basename &quot;$sf&quot;)<br>  [ &quot;$sf_base&quot; = &quot;$current_jsonl&quot; ] &amp;&amp; continue<br>  # ... sum costs and tokens<br>done &lt; &lt;(find &quot;$HOME/.claude/projects&quot; -name &quot;*.jsonl&quot; -type f -mmin -5)</pre><h3>Line 9 — — Status &amp; Recommendations</h3><p>The bottom line runs through a priority-ordered decision tree and tells you what matters right now:</p><p>MessageTriggerWhat To Do🚨 Memory almost full (92%) — Run /compact now or start a new sessionContext &gt;90%Auto-compaction is imminent. You&#39;ll lose detail.⚠️ Memory filling up (78%) — Run /compact soon to free spaceContext 75--90%Getting tight. Proactively compact before it&#39;s forced.⚡ Using memory fast (3.2K/min) — Break task into smaller stepsVelocity &gt;3K/minYour prompts/responses are large. Chunk the work.🔄 Compacted 5x — Session is long. Consider starting fresh (/clear)&gt;3 compactionsYou&#39;re losing context repeatedly. Start a new session.⚠️ 82% tool success — Errors may be causing retries, check outputSuccess &lt;90%Something is failing. Check for retry loops.✅ 2 other session(s) also running — $12.30/hr combinedOther sessions activeFYI --- your parallel sessions are spending this much.✅ All goodNothing to worry aboutCarry on.</p><p>The design philosophy: <strong>every message explains what’s happening AND what to do about it.</strong> No jargon like “cache hit rate” or unexplained numbers. If you need to act, the message tells you how.</p><h3>The Architecture: Native JSON + JSONL Hybrid</h3><p>The v4.0 script uses a two-source approach:</p><p><strong>Primary source: Claude Code’s native JSON</strong> (piped via stdin)</p><ul><li>Cost (cost.total_cost_usd) --- actual, not estimated</li><li>Context usage (context_window.*) --- percentage, token counts, window size</li><li>Duration (cost.total_duration_ms, cost.total_api_duration_ms)</li><li>Code changes (cost.total_lines_added, cost.total_lines_removed)</li><li>Model, version, session ID, transcript path</li></ul><p><strong>Secondary source: Session JSONL</strong> (file parsing, for tool stats only)</p><ul><li>Message count</li><li>Tool breakdown (Read, Edit, Bash, Write)</li><li>Tool success rate</li><li>Files touched</li></ul><p>This hybrid approach gets the best of both worlds: accurate metrics from the source of truth, plus detailed tool analytics that only exist in the transcript.</p><pre># Extract everything from native JSON in one pass<br>native=$(echo &quot;$input&quot; | jq &#39;{<br>  cost_usd:    (.cost.total_cost_usd // 0),<br>  wall_ms:     (.cost.total_duration_ms // 0),<br>  ctx_used_pct: (.context_window.used_percentage // 0),<br>  # ... 15+ more fields<br>}&#39;)</pre><pre># JSONL only for tool stats<br>tool_metrics=$(jq -s &#39;{<br>  tool_read: [.[] | select(.message.content[]?.name == &quot;Read&quot;)] | length,<br>  # ... tool breakdowns<br>}&#39; &quot;$session_file&quot;)</pre><h3>Performance: It Has to Be Fast</h3><p>A status line that lags is worse than no status line. Several optimizations keep render time negligible:</p><p><strong>Render throttling</strong>: Skip if last render was &lt;2 seconds ago.</p><pre>if [ $(( now_ts - STATUSLINE_LAST_RENDER )) -lt 2 ]; then exit 0; fi</pre><p><strong>Native JSON first</strong>: Most metrics come from a single jq extraction of the stdin payload --- no file I/O at all. Only tool stats require reading the JSONL file.</p><p><strong>Single-pass JSONL extraction</strong>: When we do read the session file, one jq -s call returns all tool metrics at once instead of making separate passes.</p><p><strong>Persistent state</strong>: Peak context, compaction count, and session start time are persisted to a .usage_state file so they survive across renders without re-scanning history.</p><p><strong>Tight aggregate window</strong>: Only scanning JSONL files modified in the last 5 minutes (not 60) means fewer files to parse for multi-session tracking.</p><h3>Setup (2 Minutes)</h3><h3>1. Save the script</h3><pre># Save statusline.sh to ~/.claude/statusline.sh<br>chmod +x ~/.claude/statusline.sh</pre><h3>2. Configure Claude Code</h3><p>Add to ~/.claude/settings.json:</p><pre>{<br>  &quot;statusLine&quot;: {<br>    &quot;type&quot;: &quot;command&quot;,<br>    &quot;command&quot;: &quot;~/.claude/statusline.sh&quot;,<br>    &quot;padding&quot;: 0<br>  }<br>}</pre><h3>3. Install dependencies</h3><pre># macOS<br>brew install jq bc</pre><pre># Ubuntu/Debian<br>apt install jq bc</pre><p>That’s it. Next time Claude Code renders, you’ll see the full dashboard.</p><h3>Why This Approach Works</h3><p>I tried the other approach first — — a separate monitoring utility. It meant:</p><ul><li>Version drift between the monitor and Claude Code</li><li>Stale data from polling intervals</li><li>Cost estimates that drifted from reality</li><li>Another process to babysit</li></ul><p>The status line script uses <strong>only</strong> what’s already there:</p><ul><li><strong>bash</strong> — — it’s your shell</li><li><strong>Claude Code’s native JSON</strong> — — piped to your script on every render</li><li><strong>Session JSONL files</strong> — — already written by Claude Code (only for tool stats)</li><li><strong>git</strong> — — you’re already in a repo</li><li><strong>jq/bc</strong> — — standard utilities</li></ul><p>No daemon. No network calls. No pricing tables to keep updated. The cost is <em>actual</em>, not estimated. Less ceremony, more clarity.</p><h3>From Numbers to Decisions: The Wave Strategy</h3><p>The status line wasn’t the end goal — — it was the <em>input</em> to a decision framework. The whole point is answering: <strong>“What can I safely hand off to Claude right now?”</strong></p><h3>The Delegation Decision Tree</h3><p>Every time I’m about to kick off a task, I glance at the status line and make a call:</p><p>Status Line SaysWhat I DoContext &lt;50%, ✅ All good<strong>Go wide.</strong> Spin up parallel sessions. Run the big refactor. Let Claude loose on multi-file changes.Context 50--75%, velocity moderate<strong>Stay focused.</strong> One session at a time. Targeted edits, not open-ended exploration.Context 75--90%, ⚠️ Memory filling up<strong>Wrap up.</strong> Finish current tasks, don&#39;t start new ones. Run /compact proactively.Context &gt;90%, 🚨 Memory almost full<strong>Compact or restart.</strong> /compact now, or start a fresh session with /clear.</p><h3>Wave Mode: Staged Orchestration</h3><p>When I have a large task — — say, implementing a full feature across 8 files — — I don’t throw it all at Claude in one shot. I run it in <strong>waves</strong>, using the status line to pace each stage:</p><p><strong>Wave 1 (Architecture)</strong>: Ask Claude to plan the approach. Low token cost, high value. Check the status line — — context should still be low.</p><p><strong>Wave 2 (Core Implementation)</strong>: Implement the main logic. This is the expensive wave. Watch ⚡ velocity/min --- if it spikes above 3K/min, you&#39;re burning context fast. Watch the Until compact timer.</p><p><strong>Wave 3 (Integration)</strong>: Wire everything together. If context is getting high from Wave 2, /compact first. The compaction counter tells you if Claude already auto-compacted (and lost detail you might need).</p><p><strong>Wave 4 (Testing &amp; Cleanup)</strong>: Run tests, fix edge cases. By now, check the aggregate line — — if other sessions are also active, your total burn rate adds up.</p><p>The 📈 Peak: 156.2K • 🔄 2x compact line tells you how many waves you&#39;ve effectively been through. Each compaction roughly marks a wave boundary where context was reset.</p><h3>Pro Tips for High-Throughput Workflows</h3><ul><li><strong>When context velocity spikes</strong>: Run /compact to reclaim context, then switch to /model sonnet for routine work. Sonnet is cheaper than Opus for output tokens.</li><li><strong>When context is high</strong>: Add “Be concise. Code only, minimal explanation.” to your CLAUDE.md --- this persistently reduces verbose output across all sessions.</li><li><strong>Long sessions</strong>: Watch the compaction counter. If it’s climbing fast (🔄 5x compact in an hour), your tasks are too broad. Break them into focused, disposable sessions.</li><li><strong>Cost-aware model switching</strong>: The 🤖 model indicator reminds you which pricing tier you&#39;re on. Use /model sonnet mid-session for tasks that don&#39;t need Opus-level reasoning and watch the $/hr rate drop.</li></ul><h3>What I Learned Running This for Months</h3><p><strong>Compaction count is a better metric than token count.</strong> My .usage_state file shows COMPACTION_COUNT=138 on one project. That&#39;s 138 times the context was auto-summarized. Each compaction loses nuance. Seeing that number climb made me change how I structure tasks --- smaller, more focused sessions instead of marathon conversations.</p><p><strong>Native JSON beats estimation.</strong> The previous version estimated cost from token counts and a pricing table. It was close but never exact, and the pricing table needed manual updates when Anthropic changed rates. Getting total_cost_usd directly eliminated an entire class of bugs.</p><p><strong>Active session detection needs a tight window.</strong> The first version counted any JSONL file modified in the last 60 minutes as an “active session.” One debugging session where I read old session files triggered false positives — — suddenly showing “12 sessions running” when only 1 was active. Tightening to 5 minutes and excluding the current session fixed this completely.</p><p><strong>Tool breakdown catches pathological patterns.</strong> When Bash calls spike (B:40+ in a short session), something is usually in a retry loop. When Write calls are high, check for duplicated file creation. The status line turns these invisible failure modes into scannable numbers.</p><p><strong>Status messages must be human-readable.</strong> Early versions showed things like “Cache 99% hit rate” and “Throttle: 2.1h 🟢.” Users (including me) misinterpreted these constantly. The current version says exactly what’s happening and what to do: “Memory filling up (78%) — — Run /compact soon to free space.” If a message needs explanation, it’s a bad message.</p><h3>Customization Ideas</h3><p>The script is ~400 lines of bash and every metric is modular. Some things to try:</p><ul><li><strong>Add per-model cost tracking</strong>: Track how much you spend on Opus vs. Sonnet per session</li><li><strong>Burn rate smoothing</strong>: Average context velocity over the last N minutes instead of session lifetime</li><li><strong>Auto-compact triggers</strong>: Use a Claude Code hook to automatically run /compact when context hits a threshold</li><li><strong>Slack/webhook alerts</strong>: Send a notification when aggregate spend crosses a threshold</li><li><strong>Session tagging</strong>: Add task labels to the status line so you know what each session is working on</li></ul><h3>Final Thought</h3><p>Sometimes the cleanest fix isn’t “one more tool” — — it’s using what you already have, better. Claude Code’s native statusline JSON was sitting there the whole time, containing everything I needed to make informed decisions about pacing, context, and cost.</p><p>~400 lines of bash. No daemon. No dependencies. Real-time visibility into every metric that matters.</p><p>If you adapt this for your workflow, I’d love to hear what you add.</p><p><strong>Repo</strong>: <a href="https://github.com/nnaveenraju/claude-code-status-line">claude-code-status-line</a></p><p><em>Built with Claude Code, tracked with this very status line.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8b1b8a936bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naveen-blog/claude-code-status-line-metrics-c8b1b8a936bd">Claude Code… Status Line Metrics</a> was originally published in <a href="https://medium.com/naveen-blog">naveen’s-blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Invoke Mulesoft flow from Java]]></title>
            <link>https://medium.com/naveen-blog/invoke-mulesoft-flow-from-java-f860a113159d?source=rss-180ff554c744------2</link>
            <guid isPermaLink="false">https://medium.com/p/f860a113159d</guid>
            <category><![CDATA[invoke-mulesoft-flow]]></category>
            <category><![CDATA[mulesoft]]></category>
            <category><![CDATA[mulesoft-callable]]></category>
            <category><![CDATA[invoke-mulesoft-from-java]]></category>
            <dc:creator><![CDATA[Naveen Raju]]></dc:creator>
            <pubDate>Thu, 26 Apr 2018 01:07:38 GMT</pubDate>
            <atom:updated>2018-04-26T01:16:35.402Z</atom:updated>
            <content:encoded><![CDATA[<p>I had a scenario where, I had to <strong>synchronously + recursively</strong> collect paged data from a REST API.</p><p>To get data as per the requirement, I had to do a loop in JAVA and call Mulesoft flow to collect data using the REST API. The following is the approach I chose to get the paged data in synchronous process.</p><blockquote><strong>Mulesoft flow code</strong></blockquote><p>&lt;flow name=”common-codeFlow”&gt; <br>……………… flow code goes here to get data from REST API…<br>&lt;/flow&gt;</p><h4>Java code to call the above “common-codeFlow” recursively to collect the data.</h4><h4>This class in consumed in the flow using a JAVA component.</h4><p>The following <strong>GetNextURIPagedData </strong>class implements <strong>Callable, FlowConstructAware, MuleContextAware </strong>to invoke the Mulesoft flow.</p><blockquote><strong>Java code in GetNextURIPagedData.java</strong></blockquote><p>public class GetNextURIPagedData implements <strong>Callable, FlowConstructAware, MuleContextAware</strong> {</p><p>MuleContext mContext;<br> FlowConstruct flowConstruct;</p><p>@Override<br> public void setMuleContext(MuleContext context) {<br> this.mContext = context;<br> }</p><p>@Override<br> public void setFlowConstruct(FlowConstruct flowConstruct) {<br> this.flowConstruct = flowConstruct; <br> }</p><p>@Override<br> public Object onCall(MuleEventContext eventContext) throws Exception {<br> <br> String strPayload = eventContext.getMessage().getPayload().toString();<br> <br> try {</p><p>MessageProcessor muleFlow = mContext.getRegistry().lookupObject(“common-codeFlow”);<br>MuleMessage muleMessage = new DefaultMuleMessage(eventContext.getMessage(), mContext);<br>System.out.println(“In Java Class : Getting data for URL : “ + muleMessage.getPayloadAsString());<br> <br>MuleEvent inputEvent = new DefaultMuleEvent(muleMessage, MessageExchangePattern.REQUEST_RESPONSE,<br>mContext.getRegistry().lookupFlowConstruct(“common-codeFlow”) ,new DefaultMuleSession() );<br>//Code to invoke the <br>MuleEvent result = muleFlow.process(inputEvent);<br><br>System.out.println(result.getMessage().getInboundProperty(“Links”).toString());</p><p>} catch (Exception e) {<br> System.out.println(e.getMessage());<br> }<br> <br> return “”;<br> }</p><p>}</p><p><em>Thank you for reading! If you enjoyed it, please clap 👏 for it.</em></p><p>-Naveen</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f860a113159d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naveen-blog/invoke-mulesoft-flow-from-java-f860a113159d">Invoke Mulesoft flow from Java</a> was originally published in <a href="https://medium.com/naveen-blog">naveen’s-blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mulesoft : SMTP : Transform, send file as email attachments]]></title>
            <link>https://medium.com/naveen-blog/mulesoft-transform-data-into-excel-csv-and-attach-the-file-to-email-dbffcd737c36?source=rss-180ff554c744------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbffcd737c36</guid>
            <category><![CDATA[email-with-attachment]]></category>
            <category><![CDATA[mulesoft-csv-excel]]></category>
            <category><![CDATA[mulesoft-esb]]></category>
            <category><![CDATA[smtp]]></category>
            <category><![CDATA[mulesoft]]></category>
            <dc:creator><![CDATA[Naveen Raju]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 04:36:51 GMT</pubDate>
            <atom:updated>2018-04-24T04:42:04.062Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will showcase the capabilities of Mulesoft to send email with CSV / Excel as attachment after dataweave transformations.</p><blockquote>SMTP Pre-config setting (GMail):</blockquote><p>For this demonstration, we will be using gmail as SMTP server to send emails.</p><p>To achieve this, we need to setup GMail to allow the account to send emails. Follow the instructions in the following google support link.</p><p><a href="https://support.google.com/mail/answer/7126229">Use IMAP to check Gmail on other email clients - Gmail Help</a></p><p>Mulesoft project setup:</p><p>Create a new project : Below is the folder structure of the new project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*G02A_wiqUzsL2CeBsc_X-A.png" /></figure><h4>The following shows the Mulesoft code related to transformation and sending email with attachment.</h4><blockquote>&lt;smtp:gmail-connector name=”Gmail” validateConnections=”true” doc:name=”Gmail” contentType=”text/html”/&gt;</blockquote><blockquote>&lt;flow name=”SMTP-Flow”&gt;</blockquote><blockquote>&lt;! — Dataweave transformation to create CSV output→</blockquote><blockquote>&lt;dw:transform-message doc:name=”Transform Message”&gt;<br>&lt;dw:set-payload&gt;&lt;![CDATA[%dw 1.0<br>%output application/csv<br> — -<br>[<br> {<br> Id: 123,<br> Name: “George”<br> },<br> {<br> Id: 456,<br> Name: “Lucas”<br> }<br>]<br>]]&gt;&lt;/dw:set-payload&gt;<br>&lt;/dw:transform-message&gt;</blockquote><blockquote>&lt;! — transform the payload to BYTE-ARRAY to attach the payload to file →</blockquote><blockquote>&lt;object-to-byte-array-transformer doc:name=”Object to Byte Array”/&gt;</blockquote><blockquote>&lt;! —The following will set the message attachment using the payload (CSV output from DW ) →</blockquote><blockquote>&lt;set-attachment attachmentName=”${mule.env} #[‘ — ‘ + flowVars.refId].csv” value=”#[payload]” contentType=”text/html” doc:name=”Attachment”/&gt;</blockquote><blockquote>&lt;! — The following will be the email body →</blockquote><blockquote>&lt;set-payload value=”#[‘Please check the attached for details.’]” doc:name=”Set Payload”/&gt;</blockquote><blockquote>&lt;! — Now the message has the attachment, the SMTP will send the message as email →</blockquote><blockquote>&lt;smtp:outbound-endpoint host=”smtp.gmail.com” port=”587&quot; user=”some-gmail@gmail.com” password=”gmail-password&quot; connector-ref=”Gmail” to=”to-emailid@gmail.com” from=”from-email@gmail.com” subject=”testng…” responseTimeout=”10000&quot; doc:name=”SMTP”/&gt;</blockquote><blockquote>&lt;/flow&gt;</blockquote><h4>For transforming data into EXCEL, using the following Dataweave:</h4><p>&lt;! — Dataweave transformation to create Excel output→</p><blockquote>&lt;dw:transform-message doc:name=”Transform Message”&gt;<br>&lt;dw:set-payload&gt;&lt;![CDATA[%dw 1.0<br>%output application/xlsx header=true<br> — -<br>{<br> Sheet1 : <br> [<br> {<br> Id: 123,<br> Name: “George”<br> },<br> {<br> Id: 456,<br> Name: “Lucas”<br> }<br> ]<br>}<br>]]&gt;&lt;/dw:set-payload&gt;<br>&lt;/dw:transform-message&gt;</blockquote><p>If you get any authentication issue using gmail as SMTP, make sure you turn on the following in goggle-account settings -&gt; Sign-in &amp; security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DkIxZqbthsjAIaZ0FshGw.png" /></figure><p>This should do the trick.</p><p>In enterprise, this may not be accepted. So you need to work with your email exchange team to get the SMTP host, port and access to send email via the setup.</p><p><em>Thank you for reading! If you enjoyed it, please clap 👏 for it.</em></p><p>-Naveen</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbffcd737c36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/naveen-blog/mulesoft-transform-data-into-excel-csv-and-attach-the-file-to-email-dbffcd737c36">Mulesoft : SMTP : Transform, send file as email attachments</a> was originally published in <a href="https://medium.com/naveen-blog">naveen’s-blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>