今日已更新 287 条资讯 | 累计 20259 条内容
关于我们

标签:#Java

找到 624 篇相关文章

AI 资讯

Java LLD: Designing Snakes and Ladders with O(1) Move Resolution

Java LLD: Designing Snakes and Ladders with O(1) Move Resolution Designing Snakes and Ladders is a classic LLD (Low-Level Design) interview question that tests your ability to write clean, maintainable, and highly performant code. While the rules are simple, naive implementations quickly fall apart under scale, concurrency, or changing business requirements. Want to go deeper? javalld.com — machine coding interview problems with working Java code and full execution traces. The Mistake Most Candidates Make Expensive Runtime Scans : Iterating through lists of snakes and ladders on every single move, turning an $O(1)$ lookup into a slow $O(N)$ search. Violating SRP : Hardcoding board mechanics, game loops, and dice rolling logic inside a single monolithic class. Tight Coupling : Binding player movement directly to the dice, making it incredibly difficult to introduce custom game rules (e.g., crooked dice or extra turns). The Right Approach Core mental model : Treat the board as a flat, pre-computed $O(1)$ lookup array where each index represents a cell and its value represents the final destination. Key entities/classes : Board , Jump (representing Snakes/Ladders), Player , Dice , Game , and MovementStrategy . Why it beats the naive approach : It decouples board setup from game loop execution, turning expensive runtime lookups into instantaneous array access. The Key Insight (Code) public class Board { private final int [] board ; // Pre-computed jump destinations public Board ( int size , List < Jump > jumps ) { this . board = IntStream . range ( 0 , size + 1 ). toArray (); jumps . forEach ( j -> board [ j . start ()] = j . end ()); // Precompute O(1) lookups } public int resolvePosition ( int current , int roll ) { int next = current + roll ; return next < board . length ? board [ next ] : current ; } } Key Takeaways DP-Style Precomputation : Pre-populating a lookup array transforms runtime search complexity from $O(N)$ to $O(1)$ time complexity per turn. Open-Closed

2026-06-26 原文 →
AI 资讯

JavaScript Arrays Methods - Part 1

What is an Array? An Array is a special object in JavaScript used to store multiple values in a single variable. Instead of creating separate variables, let student1 = " John " ; let student2 = " David " ; let student3 = " Alex " ; we can use an array: let students = [ " John " , " David " , " Alex " ]; Each value inside the array is called an element , and every element has an index starting from 0 . Index : 0 1 2 ------------------------- Array : | John | David | Alex | ------------------------- 1. Array length Definition The length property returns the total number of elements present in an array. It is not a function . It is a property of an array object. It is also writable, meaning you can change the length to increase or decrease the array size. Syntax array . length To modify the array length: array . length = newLength ; Parameters None. Returns Returns a number representing the total number of elements in the array. Internal Working Consider this array: let fruits = [ " Apple " , " Orange " , " Mango " ]; Memory representation: Index 0 → Apple 1 → Orange 2 → Mango length = 3 When JavaScript creates the array, it internally stores a special property: { 0 : "Apple" , 1 : "Orange" , 2 : "Mango" , length: 3 } Whenever you access: fruits . length JavaScript simply returns the value stored in the length property. It does not count the elements every time. This makes length very fast. Example 1 let fruits = [ " Apple " , " Orange " , " Banana " ]; console . log ( fruits . length ); Output 3 Example 2 - Updating Length let numbers = [ 10 , 20 , 30 , 40 ]; numbers . length = 2 ; console . log ( numbers ); Output [ 10 , 20 ] JavaScript removes the remaining elements. Example 3 - Increasing Length let colors = [ " Red " , " Blue " ]; colors . length = 5 ; console . log ( colors ); Output [ "Red" , "Blue" , empty × 3 ] The new positions become empty slots . Real-Time Example Imagine an E-commerce Shopping Cart . let cart = [ " Laptop " , " Mouse " , " Keyboard " ]; co

2026-06-26 原文 →
开发者

From Financial Services to Full-Stack Dev: My First 3 Months

I spent 13 years in financial services — 7 at Discover Financial, 6 at Bread Financial — consistently finishing in the top 5% of my team. I was good at my job. Really good. But in March 2026, I enrolled in Coding Temple's Full-Stack Web Development bootcamp and started building. Here's what 3 months actually looks like from zero. Month 1: HTML, CSS, and Figuring Out Why Nothing Looks Right I started where everyone starts — HTML and CSS. Built a food landing page (FoodSpot) and a multi-page event site (EventHive). Learned Flexbox, Grid, responsive design, and why box-sizing: border-box should just be the default everywhere. What I shipped: FoodSpot — food landing page EventHive — responsive multi-page event site What I earned: ✅ Web Development with HTML & CSS (Coding Temple verified badge) Month 2: JavaScript, Then Python JavaScript clicked faster than I expected. DOM manipulation, ES6+, event listeners. Then Python — and honestly, Python felt natural. The OOP concepts made sense immediately. What I shipped: Python CLI Task Manager — persistent task app with file storage, OOP, exception handling Defeat the Evil Wizard — text-based RPG with multiple classes, inheritance, combat logic, and game state management What I earned: ✅ JavaScript Mastery ✅ Python Foundations for Software Engineering ✅ Advanced Python Month 3: React React was the biggest jump. Component architecture, hooks, state management, routing. But I got through it by building something real. What I shipped: FakeStore API — a full e-commerce SPA consuming a live REST API with dynamic product rendering, client-side routing, CRUD operations, and loading/error state management What I earned: ✅ Single Page Apps with React What I Brought From Finance That Helped People underestimate what non-tech backgrounds bring to code. Here's what transferred directly: Data analysis → Debugging mindset. I spent years finding patterns in account data. Finding why code breaks is the same muscle. Process optimization → Clean

2026-06-26 原文 →
AI 资讯

How to Stream & Flatten 1GB+ JSON to CSV in the Browser Without Memory Leaks

As developers, data engineers, or analysts, we’ve all been there: you download a massive database export, a logging stack dump, or a transaction archive, only to find it's a multi-gigabyte JSON file. You try to import it into a spreadsheet or run it through a standard online converter, and boom—your browser tab freezes, crashes, or shows the dreaded "Out of Memory" screen. Even worse, if you try to use standard cloud-based online tools, you might have to wait for a 500MB upload to complete, only to hit a rigid file-size cap or, worse, compromise sensitive data privacy by uploading corporate logs or database records to a third-party server. In this guide, we will explore: Why large JSON files crash standard parsers (the V8 heap limit problem). How streaming architectures solve this by reading data chunk-by-chunk. NDJSON (JSON Lines) vs. JSON Arrays and how to stream them. A browser-native, 100% offline tool to convert large JSON to CSV instantly: Parsify's Large JSON Stream Converter . How to implement your own basic browser-based JSON streaming parser in JavaScript. 1. The Anatomy of a Memory Crash (Why JSON.parse Fails) If you are using JavaScript or Node.js, the simplest way to read and parse a JSON file is to load the file into memory and run JSON.parse(). const fs = require ( ' fs ' ); // Naive approach: Will crash on a 1GB+ file fs . readFile ( ' database-dump.json ' , ' utf8 ' , ( err , data ) => { if ( err ) throw err ; // POINT OF FAILURE: V8 Heap Out of Memory const records = JSON . parse ( data ); records . forEach ( record => { // Process record... }); }); This works fine for small config files. But once your JSON file reaches 100MB, 500MB, or 1GB+, this approach is guaranteed to trigger a fatal crash: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory Why does this happen? The String Duplication Overhead: When you load a 1GB file into memory, you first allocate ~1GB of RAM for the raw text string. The

2026-06-26 原文 →
AI 资讯

I Tracked My Body Fat for 90 Days and Built a Calculator That Actually Makes Sense

For three months, I weighed myself every morning and took body measurements every Sunday. I used a caliper, a tape measure, and a scale that probably lies to me about hydration levels. The goal wasn't to get ripped. It was to understand whether any of these measurements actually mean something day to day. The Problem With Most Health Calculators Most body fat calculators fall into one of two camps: Too simple — plug in height and weight, get a BMI number that tells you nothing about your actual composition. Too complicated — requires measurements you need a degree to take correctly, plus an email signup and a paid subscription. Neither is useful for someone who just wants to know "am I making progress?" Building Something Practical I put together a calculator that uses the Navy Method — it takes neck, waist, and hip measurements and estimates body fat percentage. The math has been around since the 80s and correlates reasonably well with DEXA scans for most people: function navyBodyFat ( gender , neck , waist , hip , height ) { if ( gender === ' male ' ) { return 86.010 * Math . log10 ( waist - neck ) - 70.041 * Math . log10 ( height ) + 36.76 } return 163.205 * Math . log10 ( waist + hip - neck ) - 97.684 * Math . log10 ( height ) - 78.387 } The inputs are simple enough that anyone can take them with a tape measure. The output gives you a ballpark number that's consistent enough to track trends over time. What 90 Days of Data Taught Me Three things stood out: Daily weight is useless; weekly trend is everything. My weight would swing 2-3 pounds daily due to water, food, and sleep. The weekly moving average was the only signal worth watching. Body fat percentage changes slowly. Like, frustratingly slowly. In 90 days of consistent training, I moved maybe 2%. But that's real — if a calculator tells you you dropped 5% body fat in a month, it's broken. Consistency beats precision. Taking measurements at the same time, under the same conditions, with the same method matter

2026-06-25 原文 →
AI 资讯

Building Rule-Validator: Why I Built a Java Annotation-Based Rule Engine After 3 Years of Fighting Business Rules

Building Rule-Validator: Why I Built a Java Annotation-Based Rule Engine After 3 Years of Fighting Business Rules Let me tell you a story. For three years, I've been fighting the same battle in enterprise Java development: business rule validation . Honestly, every time a new requirement comes in like "this order must be approved if amount > 10000 AND user level > 3 AND discount < 0.1", I'd end up with a 500-line method full of if-else that nobody wants to touch. Sound familiar? I tried every existing solution: Drools: Too heavy, requires learning a new DSL, impossible to debug Spring Validation: Great for basic validation, but can't handle complex business rules nicely Hand-written if-else: Works, but becomes unreadable after 10 rules Expression engines like Aviator: Still externalized, breaks compile-time checking So here's the thing — I learned the hard way that what Java developers actually want is simple, annotation-based, compile-safe rule validation that lives right next to your code. That's why I built rule-validator . What is Rule-Validator? Rule-validator is a lightweight Java library that lets you define business rules using annotations directly on your classes . No DSL, no external files, no magic — just simple, testable, maintainable rules. The core idea is: Each rule is a method annotated with @Rule Rules can be grouped and ordered You get full Java compile-time checking Everything stays in your code, where it belongs Here's a quick example to show you how it works: import com.github.kevinten10.rulevalidator.annotation.Rule ; import com.github.kevinten10.rulevalidator.annotation.RuleGroup ; import com.github.kevinten10.rulevalidator.core.RuleExecutor ; import com.github.kevinten10.rulevalidator.result.RuleResult ; // Define your business object public class Order { private BigDecimal amount ; private Integer userLevel ; private BigDecimal discount ; // getters and setters public BigDecimal getAmount () { return amount ; } public Integer getUserLevel ()

2026-06-25 原文 →
AI 资讯

The Frontend Is Becoming a Conversation: Where UI Engineering Goes Next

For a decade, "what's your frontend stack?" was a loaded question. jQuery vs. Backbone. Angular vs. React. Webpack vs. everything. The churn was exhausting, and a non-trivial chunk of our job was just keeping up. That era is quietly ending — not because we won the framework wars, but because the questions moved up a layer. The interesting problems in frontend today aren't about which library renders a list. They're about how rendering, data, and increasingly generation fit together. And AI is sitting right in the middle of that shift. The stack consolidated more than we admit Look at what most new production apps actually reach for in 2026: React or Svelte/Vue for the component model, with the framework wars settling into "pick one, they're all fine." A meta-framework — Next, Remix/React Router, SvelteKit, Nuxt — because nobody hand-rolls routing, data loading, and SSR anymore. TypeScript by default. Not a debate. The plain-JS greenfield project is now the exception. Server-first rendering (RSC, islands, streaming) as the baseline, with the client bundle treated as a cost to minimize rather than the center of the universe. The center of gravity moved back toward the server — but a smarter server that streams HTML, hydrates selectively, and treats the network boundary as a first-class design concern. The pendulum didn't swing back to 2010; it spiraled forward. What AI actually changed (and what it didn't) The hype says "AI writes the frontend now." The reality on the ground is more specific and more interesting. It collapsed the cost of the first 80%. Scaffolding a component, wiring a form, translating a Figma frame into JSX, writing the Tailwind for a layout — these used to be hours of work and are now minutes. That's real, and it's already changed how teams estimate. It did not collapse the last 20%. Accessibility edge cases, focus management, race conditions in async state, the weird Safari bug, the design-system invariant that isn't written down anywhere — this i

2026-06-25 原文 →
AI 资讯

How I Split PDFs in the Browser with Vue 3 and pdf-lib

Splitting a PDF is one of those features that sounds trivial until you try to build it. Users expect range input ( 1-3, 5, 7-9 ), a per-page option, multiple file downloads, and zero server involvement. I built en.sotool.top/split/ to do exactly that. Here's how it works with Vue 3 and pdf-lib . Why Client-Side? PDFs often contain sensitive information. Contracts, medical records, financial statements. Even a "simple" splitting tool should not force users to upload files to a server. Client-side benefits: No upload bandwidth or size limits No server storage or cleanup Instant processing for normal files Works offline after the page loads The tradeoff is that everything has to run in the browser, which limits the libraries you can use. The Stack Vue 3 — UI and state pdf-lib — Load, manipulate, and save PDFs File API — Read the uploaded file lucide-vue-next — Icons npm install pdf-lib Loading the PDF and Counting Pages First, read the file into an ArrayBuffer and load it with pdf-lib . import { PDFDocument } from ' pdf-lib ' const pdfFile = ref < File | null > ( null ) const totalPages = ref ( 0 ) async function handleFile ( files : File []) { if ( files . length === 0 ) return pdfFile . value = files [ 0 ] const bytes = await files [ 0 ]. arrayBuffer () const pdf = await PDFDocument . load ( bytes ) totalPages . value = pdf . getPageCount () } Now we know how many pages exist and can show the split UI. Two Split Modes I offer two ways to split: by range and per page. Mode 1: Page Range Input Users type something like 1-3, 5, 7-9 . I parse it into groups of page indices. function parseRanges ( input : string , max : number ): number [][] { const groups : number [][] = [] const parts = input . split ( ' , ' ). map ( s => s . trim ()) for ( const part of parts ) { if ( part . includes ( ' - ' )) { const [ start , end ] = part . split ( ' - ' ). map ( Number ) const pages = [] for ( let i = start ; i <= end && i <= max ; i ++ ) { pages . push ( i - 1 ) } if ( pages . len

2026-06-25 原文 →
AI 资讯

The Security Bug Every Node.js Developer Ships to Production

Last year I was doing a code review for a startup. Everything looked fine on the surface, clean code, good structure, tests passing. Then I noticed this: const query = `SELECT * FROM users WHERE email = ' ${ req . body . email } '` That's it. That's the bug. SQL injection, sitting right there in a startup that had been in production for 8 months. Nobody caught it. Not the developer, not the reviewer, not the CTO. Here's the thing, it's not that developers are careless. It's that this kind of bug is invisible until it isn't. The code works perfectly. Tests pass. Users are happy. Until someone types ' OR '1'='1 in the email field and walks straight into your database. The bugs I see most often 1. Raw SQL with user input // 🚨 This is everywhere const query = `SELECT * FROM users WHERE email = ' ${ email } '` // ✅ Use parameterized queries const query = ' SELECT * FROM users WHERE email = $1 ' db . query ( query , [ email ]) 2. Secrets in environment variables... committed to git # .env DATABASE_URL = postgres://user:actualpassword@prod-db.company.com/mydb STRIPE_SECRET = sk_live_... Then .env ends up in the repo because someone forgot to add it to .gitignore . I've seen this more times than I want to admit. GitHub's secret scanning catches some of these, but not always before someone has already cloned the repo. 3. JWT tokens that are never actually verified // 🚨 Decoding is not the same as verifying const user = jwt . decode ( token ) // ✅ Always verify const user = jwt . verify ( token , process . env . JWT_SECRET ) jwt.decode just reads the token. Anyone can forge it. jwt.verify actually checks the signature. The names are confusingly similar and the wrong one silently works in development. 4. No rate limiting on auth endpoints // 🚨 Anyone can try a million passwords app . post ( ' /login ' , async ( req , res ) => { const user = await db . findUser ( req . body . email ) // ... }) // ✅ Add rate limiting const authLimiter = rateLimit ({ windowMs : 15 * 60 * 1000 , m

2026-06-25 原文 →
AI 资讯

On programming languages, targets, and platforms

I started as a Java developer, but for some time now, I have broadened my horizons. Recently, I thought about how early languages were dedicated to a single target and platform, and now they are broadening their focus. In this post, I want to write down my thoughts in the hope that it may be useful to others, probably to my future self. Definitions You may have been wondering about the title terms. I'm pretty sure that if you read this post, you have a pretty good picture of what a programming language is. Some may disagree on some finer points or raise a hair-splitting one, but it's not a PhD thesis, only a post on my blog. I must define what I mean by target and platform in the context of this post before going further. Target A target only makes sense in the context of compiled programming languages. For example, C's target is native code , and Java's is bytecode . Platform A platform is the system that will ultimately run the target. Native code runs on the operating system; bytecode on the JVM. Early programming languages Early programming languages had a single target and platform. I mentioned C and Java, but Ruby, Python, JavaScript, etc., were all the same. Programming language Target Platform C Native code Operating system C++ Native code Operating system Java Bytecode JVM Python - Python runtime TypeScript JavaScript Browser & server-side JS JavaScript - Browser I believe it was the case for a long time. It changed at some point, though. Multi-target is the new black The first time I heard about multi-target was in Scala. Scala came from the era of single-target and targeted bytecode on the JVM platform. However, in 2015, Martin Odersky announced Scala.js, which added JavaScript to Scala's target. The original article was published on InfoWorld, but it seems to have redirection issues nowadays. Here's the introduction on a copy: Scala, developed as a functional and object-oriented language for the JVM, is now multiplatform, with developers using it in abun

2026-06-25 原文 →
AI 资讯

Compute astrology charts in the browser: no node-gyp, no .se1 files, no AGPL

If you've wired Swiss Ephemeris into a Node astrology app, you know the ritual. You npm install sweph , and now every machine needs Python plus a C/C++ toolchain, because the package compiles Swiss's C code via node-gyp at install time (make/gcc on Linux, Xcode on macOS, Visual C++ Build Tools on Windows). It works on your laptop. Then it explodes: Apple Silicon: node-gyp can't find full Xcode behind Command Line Tools. Slim Docker / CI images: no Python, no build-essential , so the install dies. Serverless: the .node binary you built locally won't load on Amazon Linux (wrong arch or glibc). Then there's the data. Neither sweph nor swisseph bundles the .se1 ephemeris files; you download them yourself and point the library at a path. The modern set is 2 MB, the full GitHub set is 100 MB. And since 2.10.1 , sweph is AGPL-3.0 (LGPL only under a professional license), a real obligation to weigh for a closed-source SaaS backend. The pure-Rust alternative XALEN Ephemeris is an analytical engine written entirely in Rust and licensed Apache-2.0. Three things make it interesting for JS/TS devs: No node-gyp. The Node addon is napi-rs, which ships prebuilt per-platform binaries via npm. No Python, no C compiler, no compile step. A real WASM build via wasm-bindgen, so you compute charts client-side in the browser: no server round-trip, no backend copyleft. Zero data files. The core math (VSOP87A, ELP2000-82, IAU precession/nutation, an 8,870-star catalog) is analytical and compiled into the binary. No .se1 to host. import init , * as xalen from " xalen-ephemeris " ; // WASM build, runs in the browser await init (); // load the .wasm module const chart = xalen . computeChart ({ datetime : " 1990-04-12T08:30:00Z " , lat : 28.6 , lon : 77.2 }); console . log ( chart ); // planet longitudes, house cusps, etc. Swiss via Node XALEN (pure Rust) Build deps node-gyp + Python + C compiler none: prebuilt binary / .wasm Runtime data .se1 files (2 to 100 MB) none, compiled in Browser / WASM

2026-06-25 原文 →
AI 资讯

A Practical Guide to Decomposing Legacy Java Monoliths

How to Decompose a Legacy Java Monolith Without Disrupting Business Operations The Java monolithic applications have been supporting businesses for years. In these applications, the entire business logic, presentation layer, and data access layer are bundled into a single unit. These architectures are functional but hard to scale, maintain, and improve due to changing business needs. An expert Java app development company helps growing organizations in addressing this issue through Java modernization services. Instead of developing a whole software application from scratch, firms can transform their software in stages with the right boundaries. The biggest challenge here is to determine where to make those cuts in a bundle. Poorly chosen service boundaries create operational complexity issues and long-term maintenance problems. Understanding how to identify seams in the monolith application helps in achieving modernization successfully. Let's take a look at what contributes to the success of monolith decomposing and how organizations can approach it wisely. Why Organizations Are Modernizing Legacy Java Monoliths The legacy Java monolith applications were built during a time when monolithic architecture was common. They were optimized for easy deployment and centralized management. But today, businesses require flexibility. This is due to challenges such as Slow release cycles Increasing maintenance costs Limited scalability Complex dependency management Difficult onboarding new developers Growing technical debt These issues have increased the demand for software architecture modernization in business sectors. Modern architecture gives the following advantages to the teams: Deploy features independently Scale services individually Improve system resilience Accelerate development cycles Support cloud-native environments The objective of architecture modernization is to create a technical foundation that supports future business growth. Understanding business goals of

2026-06-25 原文 →
AI 资讯

React useIsomorphicLayoutEffect: Fix the SSR useLayoutEffect Warning (2026)

You added a useLayoutEffect to measure a tooltip, shipped it, and the next time your Next.js (or Remix, or Gatsby) dev server rendered a page on the server, the console lit up: Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. The warning is correct, the suggested fix ("only use it on the client") is unhelpful, and the obvious workaround — just switch to useEffect — quietly reintroduces the visual bug you used useLayoutEffect to kill in the first place. useIsomorphicLayoutEffect is the small hook that resolves the standoff. This post explains exactly why the warning happens, why the two naive fixes are both wrong, and what the one-line hook actually does. Why useLayoutEffect Exists At All React gives you two effect hooks that look nearly identical: useEffect runs after the browser has painted. Its callback is queued and fires asynchronously once the frame is on screen. useLayoutEffect runs before the browser paints, synchronously, right after React has mutated the DOM but before the user sees anything. That timing difference is the whole point. If you need to read layout — getBoundingClientRect , scrollHeight , the measured width of a node — and then write a style based on it, you have to do it before paint. Otherwise the user sees one frame of the wrong layout, then a flicker as your useEffect corrects it. The canonical example is a tooltip that has to position itself relative to its own measured size: function Tooltip ({ targetRect , children }) { const ref = useRef < HTMLDivElement > ( null ); const [ pos , setPos ] = useState ({ top : 0 , left : 0 }); useLayoutEffect (() => { const { height , width } = ref . current ! . getBoundingClientRect (); // place the tooltip above the target, centered s

2026-06-25 原文 →
AI 资讯

Why I Still Believe in Zero-Cost BFF Layers After 6 Months (And What Broke)

Why I Still Believe in Zero-Cost BFF Layers After 6 Months (And What Broke) Honestly, I didn't expect to be writing this article. Six months ago, I built capa-bff — a zero-cost BFF framework that won a hackathon gold medal — and I thought I had it all figured out. "This is perfect," I told myself. "Zero configuration, works with any Spring Boot app, solves all the frontend aggregation problems." Spoiler alert: It didn't. Don't get me wrong — it's still great for what it is. But here's the thing about building developer tools: the real world has a way of humbling you. Let me walk you through what I learned, what works, what doesn't, and who should actually use this thing. What Even Is a BFF Anyway? If you're new to the term, BFF stands for Backend For Frontend . It's that intermediate layer between your frontend clients (web, mobile, mini-programs) and your backend services. The idea is simple: instead of making the frontend stitch together data from multiple backend APIs, you have this middle layer that does it for you. ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ Frontend │ -> │ BFF │ -> │ Backend │ │ (Web/Mobile)│ │ Aggregation │ │ Services │ └─────────────┘ └─────────────┘ └─────────────┘ The benefits are clear: Fewer network calls from the client Customized responses for each client type Better caching opportunities One place to handle auth/transformations But here's the catch most articles don't tell you: adding a BFF layer means another service to maintain , another deployment , another thing that can break . For small teams and startups, that cost can feel too high. That's exactly why I built capa-bff: I wanted a zero-cost BFF layer that you can just drop into your existing Spring Boot app. No new service, no extra deployment — just add the dependency and start aggregating APIs. How It Actually Works (Code Example) Let me show you the basics. With capa-bff, you define your aggregation in a simple annotation: @BffRoute ( path = "/user-dashboard" ) public

2026-06-25 原文 →
AI 资讯

How I built an end-to-end encrypted pastebin (and why the server can’t read your text)

got annoyed that pastebin and similar sites log everything and keep your text forever, so i built one where the server literally cant read what you paste. heres how the encryption actually works and what i learned building it the problem most paste sites work like this: you type something, it goes to their server as plain text, and it sits in their database. they can read it. their employees can read it. anyone who breaches them can read it. and a lot of them keep it forever even after you think its gone. i didnt want to just promise not to look at your stuff. i wanted it so that i cant look even if i wanted to. the idea: encrypt before it leaves the browser the trick is that all the encryption happens on your side, in the browser, before anything gets sent. the server only ever sees scrambled bytes. the key never touches the server at all, it lives in the part of the url after the # , which browsers dont send in requests. so the flow is basically: you paste text browser generates a random key text gets encrypted with that key only the encrypted blob goes to the server the key gets stuck in the link after a # whoever opens the link decrypts it locally the actual code modern browsers have the Web Crypto API built in, so you dont need any library for this. heres the encrypt part, stripped down: \ `js async function encrypt(text) { const key = await crypto.subtle.generateKey( { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"] ); const iv = crypto.getRandomValues(new Uint8Array(12)); const encoded = new TextEncoder().encode(text); const ciphertext = await crypto.subtle.encrypt( { name: "AES-GCM", iv }, key, encoded ); // export the key so we can put it in the url const rawKey = await crypto.subtle.exportKey("raw", key); return { ciphertext, iv, rawKey }; } ` \ the ciphertext and iv go to the server. the rawKey gets base64'd and dropped into the link after the # . decrypting is just the same thing in reverse with crypto.subtle.decrypt . the thing that tripped

2026-06-25 原文 →
AI 资讯

Inbox Zero for Devs: How I Built a JavaScript Script to Destroy Gmail Spam

Hey dev community! 👋 As developers, our inboxes often turn into a graveyard of job alerts (LinkedIn, Indeed, ZipRecruiter) and tech newsletters we subscribe to with the intention of "reading later" but never actually open. The result? Important emails get lost, and we get the dreaded "Account storage is almost full" notification. Recently, I hit that wall. I had thousands of accumulated emails. While Gmail allows you to create filters for incoming mail, it doesn't have a native feature to say: "Delete this email automatically after 7 days" . So, I decided to solve it the way we solve everything: by writing some code. 🛠️ The Solution: Google Apps Script + JavaScript Since the Google Workspace ecosystem runs on a JavaScript-based environment, I put together a custom script. Fun fact: a simple loop originally failed due to Google's strict 6-minute execution limit. To fix this, I optimized the code to process emails in batches of 100 , preventing the server from timing out. Here is the final production-ready script: function cleanSpamTsunami() { // 1. Loop to delete ALL Job Board emails in batches of 100 var continueJobSearch = true; while (continueJobSearch) { var jobThreads = GmailApp.search('computrabajo OR indeed OR linkedin OR OCC OR neuvoo OR talent.com OR jooble', 0, 100); if (jobThreads.length > 0) { Logger.log('Deleting a batch of ' + jobThreads.length + ' job alert emails...'); GmailApp.moveThreadsToTrash(jobThreads); } else { Logger.log('No more job alerts found!'); continueJobSearch = false; // Break the loop } } // 2. Loop to delete old Newsletters (older than 7 days) in batches of 100 var continueNewsletters = true; while (continueNewsletters) { var newsletterThreads = GmailApp.search('unsubscribe OR "cancelar suscripción" older_than:7d', 0, 100); if (newsletterThreads.length > 0) { Logger.log('Deleting a batch of ' + newsletterThreads.length + ' old newsletters...'); GmailApp.moveThreadsToTrash(newsletterThreads); } else { Logger.log('No more old newslett

2026-06-25 原文 →
AI 资讯

Your @EventListener Fires Before the Transaction Commits⚙️

Your domain event fires. Your notification service queries the DB for the entity that just got saved. It finds nothing. You add a log line. It starts working. You remove the log. It breaks again. That's not a race condition. That's @EventListener . What's actually happening Spring's @EventListener fires synchronously, inside the calling thread, before the transaction commits. The DB row exists in Hibernate's session — but it hasn't been flushed and committed yet. Other connections, including the one your listener opens when it calls findById , can't see it. The log statement "fixes" it because the delay gives Hibernate time to flush. Remove the log, the flush doesn't happen in time, and you're back to an empty Optional . Here's the broken setup: @Component public class OrderEventListener { @EventListener // fires MID-TRANSACTION, before commit public void onOrderCreated ( OrderCreatedEvent event ) { // Transaction not committed yet. // Other DB connections see nothing. Order order = orderRepository . findById ( event . getOrderId ()) . orElseThrow (); // ← throws here, row doesn't exist yet notificationService . notifyCustomer ( order ); } } The obvious fix and what it costs you Spring ships @TransactionalEventListener for exactly this. Set phase = TransactionPhase.AFTER_COMMIT and the listener fires after the transaction commits. The row is visible. findById returns the order. Problem solved. @Component public class OrderEventListener { @TransactionalEventListener ( phase = TransactionPhase . AFTER_COMMIT ) public void onOrderCreated ( OrderCreatedEvent event ) { // Transaction committed. All connections see the row. Order order = orderRepository . findById ( event . getOrderId ()) . orElseThrow (); // ← works fine notificationService . notifyCustomer ( order ); } } But the trade-off is real. Your listener is now decoupled from the transaction. If the listener fails — notification service is down, the email throws, the external API times out — the transaction alrea

2026-06-25 原文 →